<template>
  <!-- 这里添加你的模板内容 -->
  <div>
    <div
      v-if="phase === 'preparation'"
      class="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50/50 to-indigo-50"
    >
      <div class="container mx-auto px-4 py-8">
        <!-- 准备阶段顶部返回区域 -->
        <div class="flex items-center justify-between mb-6">
          <Button
            :disabled="preparationCountdown <= 1"
            class="flex items-center gap-2 text-slate-600 hover:text-slate-800 hover:bg-slate-100 transition-all duration-200"
            variant="ghost"
            @click="handleBackToSelection"
          >
            <ArrowLeft class="w-4 h-4"/>
            {{ t("preparation.backToSelection") }}
          </Button>

          <div class="flex items-center gap-2">
            <Badge class="px-3 py-1" variant="outline">
              {{
                battleMode === "team"
                  ? t("preparation.teamMode")
                  : t("preparation.soloMode")
              }}
            </Badge>
            <Badge
              class="px-3 py-1 bg-orange-50 text-orange-600 border-orange-200"
              variant="outline"
            >
              {{ t("preparation.preparing") }}
            </Badge>
          </div>
        </div>

        <Card
          class="w-full max-w-2xl flex items-center bg-white/90 backdrop-blur-sm border-2 border-blue-200 shadow-2xl"
          style="margin: auto"
        >
          <CardContent class="p-12 text-center space-y-8">
            <!-- 对手信息 -->
            <div class="space-y-4">
              <div
                :class="`w-24 h-24 mx-auto rounded-full bg-gradient-to-br ${selectedAI?.bgGradient} border-4 border-white shadow-lg flex items-center justify-center text-4xl`"
              >
                {{ selectedAI?.emoji }}
              </div>
              <div>
                <h2 class="text-2xl font-bold text-slate-800 mb-2">
                  {{ t("preparation.vs", {name: selectedAI?.name}) }}
                </h2>
                <p class="text-slate-600 mb-3">
                  {{ selectedAI?.description }}
                </p>
                <div class="flex justify-center gap-2">
                  <Badge
                    v-for="(specialty, index) in selectedAI?.specialties"
                    :key="index"
                    class="text-xs"
                    variant="secondary"
                  >
                    {{ specialty }}
                  </Badge>
                </div>
              </div>
            </div>

            <!-- 对战模式信息 -->
            <div
              class="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-lg p-6 border border-blue-200"
            >
              <h3 class="font-semibold text-lg mb-3 text-slate-800">
                {{
                  battleMode === "team"
                    ? t("preparation.teamBattleMode")
                    : t("preparation.soloBattleMode")
                }}
              </h3>
              <div class="grid grid-cols-2 gap-4 text-sm">
                <div class="flex items-center gap-2">
                  <Timer class="w-4 h-4 text-blue-600"/>
                  <span>{{
                      t("preparation.rounds", {
                        count: battleMode === "team" ? 6 : 5,
                      })
                    }}</span>
                </div>
                <div class="flex items-center gap-2">
                  <Zap class="w-4 h-4 text-yellow-600"/>
                  <span>{{
                      t("preparation.secondsPerRound", {
                        count: battleMode === "team" ? 20 : 15,
                      })
                    }}</span>
                </div>
                <div class="flex items-center gap-2">
                  <Target class="w-4 h-4 text-green-600"/>
                  <span>{{ t("preparation.mixedQuestionTypes") }}</span>
                </div>
                <div class="flex items-center gap-2">
                  <Trophy class="w-4 h-4 text-purple-600"/>
                  <span>{{ t("preparation.realTimeScoring") }}</span>
                </div>
              </div>
            </div>

            <!-- 倒计时 -->
            <div class="space-y-4">
              <p class="text-slate-600 font-medium">
                {{ t("preparation.battleStartingSoon") }}
              </p>
              <div class="relative">
                <div
                  class="w-32 h-32 mx-auto rounded-full bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center shadow-2xl"
                >
                  <span class="text-6xl font-bold text-white">
                    {{ preparationCountdown || "🚀" }}
                  </span>
                </div>
                <!-- 暂时移除动画效果 -->
                <div
                  v-if="preparationCountdown > 0"
                  class="absolute inset-0 rounded-full border-4 border-blue-400"
                />
              </div>

              <p
                v-if="preparationCountdown > 0"
                :key="`text-${preparationCountdown}`"
                class="text-xl font-semibold text-slate-700"
              >
                {{ getCountdownText(preparationCountdown) }}
              </p>
              <p
                v-else
                class="text-xl font-bold text-transparent bg-gradient-to-r from-green-600 to-emerald-600 bg-clip-text"
              >
                {{ t("preparation.startBattle") }}
              </p>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>

    <div
      v-if="phase === 'selection'"
      class="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50/50 to-indigo-50"
    >
      <div class="container mx-auto px-4 py-8">
        <motion.div
          :animate="{ opacity: 1, y: 0 }"
          :initial="{ opacity: 0, y: 20 }"
          :transition="{ duration: 0.6 }"
        >
          <!-- Header-->
          <div class="flex flex-col items-center justify-center mb-8">
            <div class="w-full flex justify-start mb-4">
              <Button
                class="flex items-center gap-2"
                variant="ghost"
                @click="onBack"
              >
                <ArrowLeft class="w-4 h-4"/>
                {{ t("selection.backToHome") }}
              </Button>
            </div>
            <div class="flex items-center justify-center gap-3">
              <div
                class="w-10 h-10 bg-gradient-to-br from-blue-600 to-purple-600 rounded-xl flex items-center justify-center shadow-lg"
              >
                <Swords class="w-6 h-6 text-white"/>
              </div>
              <div class="text-center">
                <h1
                  class="text-2xl font-bold bg-gradient-to-r from-blue-700 to-purple-700 bg-clip-text text-transparent"
                >
                  {{ t("selection.title") }}
                </h1>
                <p class="text-slate-600">{{ t("selection.subtitle") }}</p>
              </div>
            </div>
          </div>

          <!--     Tabs-->
          <Tabs
            class-name="space-y-6 w-full"
            defaultValue="solo"
            @update:value="handleTabChange"
          >
            <TabsList
              v-if="false"
              class="grid w-full grid-cols-4 bg-white/70 backdrop-blur-sm border border-slate-200 shadow-sm h-12 p-1"
            >
              <TabsTrigger
                class="flex items-center justify-center gap-2 h-10 px-3 py-2 data-[state=active]:bg-gradient-to-r data-[state=active]:from-blue-600 data-[state=active]:to-purple-600 data-[state=active]:text-white data-[state=active]:shadow-md transition-all duration-200"
                value="solo"
              >
                <Gamepad2 class="w-4 h-4 flex-shrink-0"/>
                <span class="leading-none text-sm">{{
                    t("selection.soloBattle")
                  }}</span>
              </TabsTrigger>
              <TabsTrigger
                class="flex items-center justify-center gap-2 h-10 px-3 py-2 data-[state=active]:bg-gradient-to-r data-[state=active]:from-blue-600 data-[state=active]:to-purple-600 data-[state=active]:text-white data-[state=active]:shadow-md transition-all duration-200"
                value="team"
              >
                <Users class="w-4 h-4 flex-shrink-0"/>
                <span class="leading-none text-sm">{{
                    t("selection.teamBattle")
                  }}</span>
              </TabsTrigger>
              <TabsTrigger
                class="flex items-center justify-center gap-2 h-10 px-3 py-2 data-[state=active]:bg-gradient-to-r data-[state=active]:from-green-600 data-[state=active]:to-emerald-600 data-[state=active]:text-white data-[state=active]:shadow-md transition-all duration-200 relative"
                value="pvp"
              >
                <UserPlus class="w-4 h-4 flex-shrink-0"/>
                <span class="leading-none text-sm">{{
                    t("selection.pvp")
                  }}</span>
                <div
                  class="absolute -top-1 -right-1 w-2 h-2 bg-red-500 rounded-full animate-pulse"
                ></div>
              </TabsTrigger>
              <TabsTrigger
                class="flex items-center justify-center gap-2 h-10 px-3 py-2 data-[state=active]:bg-gradient-to-r data-[state=active]:from-yellow-600 data-[state=active]:to-orange-600 data-[state=active]:text-white data-[state=active]:shadow-md transition-all duration-200"
                value="leaderboard"
              >
                <Trophy class="w-4 h-4 flex-shrink-0"/>
                <span class="leading-none text-sm">{{
                    t("selection.leaderboard")
                  }}</span>
              </TabsTrigger>
            </TabsList>

            <!-- Solo Battle Tab -->
            <TabsContent class-name="space-y-6" value="solo">
              <!-- AI对手选择 -->
              <Card
                class="bg-white/70 backdrop-blur-sm border-slate-200 shadow-lg"
              >
                <CardHeader>
                  <CardTitle class="flex items-center gap-2">
                    <Bot class="w-5 h-5 text-blue-600"/>
                    {{ t("selection.selectAIOpponent") }}
                  </CardTitle>
                  <CardDescription>
                    {{ t("selection.aiDescription") }}
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div class="grid md:grid-cols-2 gap-6">
                    <div
                      v-for="ai in aiOpponents"
                      :key="ai.id"
                      class="hover:scale-[1.02] active:scale-[0.98] transition-transform duration-300"
                    >
                      <Card
                        class="hover:shadow-lg bg-white/80 transition-all duration-300 border-2 hover:border-blue-200"
                      >
                        <CardContent class="p-6">
                          <div class="flex items-start justify-between gap-4">
                            <div class="flex items-start gap-4 flex-1">
                              <div class="text-5xl">{{ ai.emoji }}</div>
                              <div class="flex-1">
                                <div class="flex items-center gap-2 mb-2">
                                  <h3 class="text-lg font-semibold">
                                    {{ ai.name }}
                                  </h3>
                                  <Badge :class="ai.color" variant="outline">
                                    Lv.{{ ai.level }}
                                  </Badge>
                                  <Badge
                                    class="text-xs bg-slate-100 text-slate-600"
                                    variant="secondary"
                                  >
                                    {{
                                      t("selection.winRate", {
                                        rate: Math.round(ai.difficulty * 100),
                                      })
                                    }}
                                  </Badge>
                                </div>
                                <p class="text-sm text-slate-600 mb-2">
                                  {{ ai.description }}
                                </p>
                                <p class="text-xs text-slate-500 mb-3">
                                  {{ ai.personality }}
                                </p>
                                <div class="flex items-center gap-1 mb-3">
                                  <span
                                    v-for="i in ai.level"
                                    :key="i"
                                    class="w-3 h-3 fill-yellow-400 text-yellow-400"
                                  >★</span
                                  >
                                  <span class="text-xs text-slate-500 ml-2">
                                    {{
                                      t("selection.aiStrength", {
                                        level: ai.level,
                                      })
                                    }}
                                  </span>
                                </div>
                                <div class="space-y-2">
                                  <p class="text-xs font-medium text-slate-700">
                                    {{ t("selection.specialties") }}
                                  </p>
                                  <div class="flex flex-wrap gap-1">
                                    <Badge
                                      v-for="(
                                        specialty, index
                                      ) in ai.specialties"
                                      :key="index"
                                      class="text-xs bg-blue-100 text-blue-700 border-blue-200"
                                      variant="secondary"
                                    >
                                      {{ specialty }}
                                    </Badge>
                                  </div>
                                </div>
                              </div>
                            </div>
                            <div class="flex-shrink-0">
                              <Button
                                class="bg-gradient-to-r from-blue-50 to-purple-50 border-blue-200 text-blue-700 hover:bg-gradient-to-r hover:from-blue-100 hover:to-purple-100 hover:border-blue-300 px-4 transition-all duration-300"
                                size="sm"
                                variant="outline"
                                @click="startSoloBattle(ai)"
                              >
                                <Users class="w-4 h-4 mr-1"/>
                                {{ t("selection.startBattle") }}
                              </Button>
                            </div>
                          </div>
                        </CardContent>
                      </Card>
                    </div>
                  </div>
                </CardContent>
              </Card>

              <!-- 对战说明 -->
              <Card
                class="bg-gradient-to-r from-blue-50 to-indigo-50 border-blue-200"
              >
                <CardContent class="p-6">
                  <h3
                    class="text-lg font-semibold mb-4 flex items-center gap-2"
                  >
                    <Target class="w-5 h-5 text-blue-600"/>
                    {{ t("selection.soloBattleRules") }}
                  </h3>
                  <div class="grid md:grid-cols-3 gap-4 text-sm mb-6">
                    <div class="flex items-start gap-2">
                      <Circle
                        class="w-4 h-4 text-blue-500 mt-1 flex-shrink-0"
                      />
                      <div>
                        <p class="font-medium">
                          {{ t("selection.challengeRounds") }}
                        </p>
                        <p class="text-slate-600">
                          {{ t("selection.challengeDescription") }}
                        </p>
                      </div>
                    </div>
                    <div class="flex items-start gap-2">
                      <Timer
                        class="w-4 h-4 text-green-500 mt-1 flex-shrink-0"
                      />
                      <div>
                        <p class="font-medium">
                          {{ t("selection.timedQuestions") }}
                        </p>
                        <p class="text-slate-600">
                          {{ t("selection.timedQuestionsDescription") }}
                        </p>
                      </div>
                    </div>
                    <div class="flex items-start gap-2">
                      <Trophy
                        class="w-4 h-4 text-yellow-500 mt-1 flex-shrink-0"
                      />
                      <div>
                        <p class="font-medium">
                          {{ t("selection.smartMatching") }}
                        </p>
                        <p class="text-slate-600">
                          {{ t("selection.smartMatchingDescription") }}
                        </p>
                      </div>
                    </div>
                  </div>

                  <!-- 题型展示 -->
                  <div class="border-t border-blue-200/50 pt-4">
                    <h4 class="font-medium text-blue-700 mb-3">
                      {{ t("selection.questionTypes", {count: 12}) }}
                    </h4>
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-2 text-xs">
                      <div
                        v-for="(type, index) in questionTypes"
                        :key="index"
                        :class="`px-2 py-1 rounded-full text-center ${type.color}`"
                      >
                        {{ type.name }}
                      </div>
                    </div>
                    <p class="text-xs text-slate-500 mt-3">
                      {{ t("selection.questionTypesNote") }}
                    </p>
                  </div>
                </CardContent>
              </Card>
            </TabsContent>

            <!-- Team Battle Tab -->
            <TabsContent class-name="space-y-6" value="team">
              <div class="grid lg:grid-cols-2 gap-6">
                <!-- 团队配置 -->
                <Card
                  class="bg-white/70 backdrop-blur-sm border-slate-200 shadow-lg"
                >
                  <CardHeader>
                    <CardTitle class="flex items-center gap-2">
                      <Users class="w-5 h-5 text-purple-600"/>
                      {{ t("selection.formTeam") }}
                    </CardTitle>
                    <CardDescription
                    >{{ t("selection.formTeamDescription") }}
                    </CardDescription>
                  </CardHeader>
                  <CardContent class="space-y-4">
                    <div>
                      <label class="text-sm font-medium mb-2 block">
                        {{ t("selection.teamSize") }}
                      </label>
                      <div class="grid grid-cols-2 gap-3">
                        <Button
                          :class="`h-16 transition-all duration-300 ${
                            selectedTeamSize === 2
                              ? 'bg-slate-600 hover:bg-slate-700 text-white shadow-md border-0'
                              : 'bg-white hover:bg-slate-50 border-slate-300 text-slate-700 hover:border-slate-400'
                          }`"
                          :variant="
                            selectedTeamSize === 2 ? 'default' : 'outline'
                          "
                          @click="changeSelectedTeamSize(2)"
                        >
                          <div class="text-center">
                            <div class="text-lg">2v2</div>
                            <div class="text-xs opacity-80">
                              {{ t("selection.squadMode") }}
                            </div>
                          </div>
                        </Button>
                        <Button
                          :class="`h-16 transition-all duration-300 ${
                            selectedTeamSize === 3
                              ? 'bg-slate-600 hover:bg-slate-700 text-white shadow-md border-0'
                              : 'bg-white hover:bg-slate-50 border-slate-300 text-slate-700 hover:border-slate-400'
                          }`"
                          :variant="
                            selectedTeamSize === 3 ? 'default' : 'outline'
                          "
                          @click="changeSelectedTeamSize(3)"
                        >
                          <div class="text-center">
                            <div class="text-lg">
                              {{
                                t("selection.teamSizeDisplay", {
                                  size: selectedTeamSize,
                                })
                              }}
                            </div>
                            <div class="text-xs opacity-80">
                              {{ t("selection.teamMode") }}
                            </div>
                          </div>
                        </Button>
                      </div>
                    </div>

                    <div>
                      <label class="text-sm font-medium mb-2 block">
                        {{ t("selection.yourTeam") }}
                      </label>
                      <div class="space-y-2">
                        <div
                          v-for="(member, index) in playerTeam.slice(
                            0,
                            selectedTeamSize
                          )"
                          :key="index"
                          class="flex items-center gap-3 p-3 bg-blue-50 rounded-lg"
                        >
                          <div
                            class="w-8 h-8 bg-blue-600 rounded-full flex items-center justify-center text-white text-sm font-semibold"
                          >
                            {{ index === 0 ? t("selection.you") : `A${index}` }}
                          </div>
                          <span class="font-medium">{{ member }}</span>
                          <Badge
                            v-if="index === 0"
                            class="ml-auto"
                            variant="outline"
                          >
                            {{ t("selection.captain") }}
                          </Badge>
                        </div>
                      </div>
                    </div>
                  </CardContent>
                </Card>

                <!-- AI对手选择 -->
                <Card
                  class="bg-white/70 backdrop-blur-sm border-slate-200 shadow-lg"
                >
                  <CardHeader>
                    <CardTitle class="flex items-center gap-2">
                      <Bot class="w-5 h-5 text-red-600"/>
                      {{ t("selection.selectAITeam") }}
                    </CardTitle>
                    <CardDescription
                    >{{ t("selection.selectAITeamDescription") }}
                    </CardDescription>
                  </CardHeader>
                  <CardContent>
                    <div class="space-y-4">
                      <div
                        v-for="ai in tm('aiOpponents')"
                        :key="rt('ai.id')"
                        class="hover:scale-[1.02] active:scale-[0.98] transition-transform duration-300"
                      >
                        <Card
                          class="hover:shadow-lg bg-white/80 transition-all duration-300"
                        >
                          <CardContent class="p-4">
                            <div
                              class="flex items-center justify-between gap-4"
                            >
                              <div class="flex items-center gap-3 flex-1">
                                <div class="text-3xl">{{ ai.emoji }}</div>
                                <div class="flex-1">
                                  <div class="flex items-center gap-2 mb-1">
                                    <h3 class="font-semibold">
                                      {{
                                        t("selection.aiTeam", {name: ai.name})
                                      }}
                                    </h3>
                                    <Badge
                                      :class="rt('ai.color')"
                                      variant="outline"
                                    >
                                      {{ selectedTeamSize }}v{{
                                        selectedTeamSize
                                      }}
                                    </Badge>
                                  </div>
                                  <p class="text-sm text-slate-600 mb-2">
                                    {{ rt("ai.description") }}
                                  </p>
                                  <div class="flex items-center gap-1">
                                    <span
                                      v-for="i in rt('ai.level')"
                                      :key="rt('i')"
                                      class="w-3 h-3 fill-yellow-400 text-yellow-400"
                                    >★</span
                                    >
                                  </div>
                                </div>
                              </div>
                              <div class="flex-shrink-0">
                                <Button
                                  class="bg-slate-50 border-slate-200 text-slate-700 hover:bg-slate-100 hover:text-slate-900 px-4"
                                  size="sm"
                                  variant="outline"
                                  @click="startTeamBattle(rt('ai'))"
                                >
                                  <Users class="w-4 h-4 mr-1"/>
                                  {{ t("selection.startBattle") }}
                                </Button>
                              </div>
                            </div>
                          </CardContent>
                        </Card>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </div>

              <!-- 团队对战说明 -->
              <Card
                class="bg-gradient-to-r from-purple-50 to-pink-50 border-purple-200"
              >
                <CardContent class="p-6">
                  <h3
                    class="text-lg font-semibold mb-4 flex items-center gap-2"
                  >
                    <Users class="w-5 h-5 text-purple-600"/>
                    {{ t("selection.teamBattleRules") }}
                  </h3>
                  <div class="grid md:grid-cols-3 gap-4 text-sm mb-6">
                    <div class="flex items-start gap-2">
                      <Circle
                        class="w-4 h-4 text-purple-500 mt-1 flex-shrink-0"
                      />
                      <div>
                        <p class="font-medium">
                          {{ t("selection.teamChallengeRounds") }}
                        </p>
                        <p class="text-slate-600">
                          {{ t("selection.teamChallengeDescription") }}
                        </p>
                      </div>
                    </div>
                    <div class="flex items-start gap-2">
                      <Timer
                        class="w-4 h-4 text-green-500 mt-1 flex-shrink-0"
                      />
                      <div>
                        <p class="font-medium">
                          {{ t("selection.teamTimePerQuestion") }}
                        </p>
                        <p class="text-slate-600">
                          {{ t("selection.teamTimePerQuestionDescription") }}
                        </p>
                      </div>
                    </div>
                    <div class="flex items-start gap-2">
                      <Trophy
                        class="w-4 h-4 text-yellow-500 mt-1 flex-shrink-0"
                      />
                      <div>
                        <p class="font-medium">
                          {{ t("selection.teamPoints") }}
                        </p>
                        <p class="text-slate-600">
                          {{ t("selection.teamPointsDescription") }}
                        </p>
                      </div>
                    </div>
                  </div>

                  <!-- 团队模式特色 -->
                  <div class="border-t border-purple-200/50 pt-4">
                    <h4 class="font-medium text-purple-700 mb-3">
                      {{ t("selection.teamModeFeatures") }}
                    </h4>
                    <div class="grid grid-cols-2 gap-3 text-sm">
                      <div class="flex items-center gap-2">
                        <div class="w-2 h-2 bg-purple-500 rounded-full"></div>
                        <span>{{ t("selection.autoDifficultyIncrease") }}</span>
                      </div>
                      <div class="flex items-center gap-2">
                        <div class="w-2 h-2 bg-pink-500 rounded-full"></div>
                        <span>{{ t("selection.sequenceLengthIncrease") }}</span>
                      </div>
                      <div class="flex items-center gap-2">
                        <div class="w-2 h-2 bg-purple-500 rounded-full"></div>
                        <span>{{ t("selection.complexMath") }}</span>
                      </div>
                      <div class="flex items-center gap-2">
                        <div class="w-2 h-2 bg-pink-500 rounded-full"></div>
                        <span>{{ t("selection.moreOptions") }}</span>
                      </div>
                    </div>
                    <p class="text-xs text-slate-500 mt-3">
                      {{ t("selection.teamModeNote") }}
                    </p>
                  </div>
                </CardContent>
              </Card>
            </TabsContent>

            <!-- PvP Matchmaking Tab -->
            <TabsContent class="space-y-6" value="pvp">
              <div class="grid gap-6">
                <!-- PvP Mode Selection -->
                <div class="flex gap-2 p-1 bg-gray-100 rounded-lg">
                  <button
                    :class="`flex-1 flex items-center justify-center gap-2 px-4 py-3 rounded-md transition-all ${
                      pvpMode === 'matchmaking'
                        ? 'bg-white shadow-sm text-gray-900'
                        : 'text-gray-600 hover:text-gray-900'
                    }`"
                    @click="pvpMode = 'matchmaking'"
                  >
                    <Search class="w-4 h-4"/>
                    {{ t("selection.matchmaking") }}
                  </button>
                  <button
                    :class="`flex-1 flex items-center justify-center gap-2 px-4 py-3 rounded-md transition-all ${
                      pvpMode === 'rooms'
                        ? 'bg-white shadow-sm text-gray-900'
                        : 'text-gray-600 hover:text-gray-900'
                    }`"
                    @click="pvpMode = 'rooms'"
                  >
                    <Users class="w-4 h-4"/>
                    {{ t("selection.roomBattle") }}
                  </button>
                  <button
                    :class="`flex-1 flex items-center justify-center gap-2 px-4 py-3 rounded-md transition-all ${
                      pvpMode === 'friends'
                        ? 'bg-white shadow-sm text-gray-900'
                        : 'text-gray-600 hover:text-gray-900'
                    }`"
                    @click="pvpMode = 'friends'"
                  >
                    <Heart class="w-4 h-4"/>
                    {{ t("selection.friendBattle") }}
                  </button>
                </div>

                <!-- Matchmaking Content -->
                <div v-if="pvpMode === 'matchmaking'" class="space-y-6">
                  <div v-if="!isSearching && !matchFound" class="space-y-6">
                    <!-- Match Settings -->
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                      <!-- Match Mode -->
                      <div
                        class="opacity-100 transform-none transition-all duration-300"
                      >
                        <Card
                          class="h-full bg-white/80 backdrop-blur-sm border border-slate-200 shadow-sm hover:shadow-md transition-all duration-300"
                        >
                          <CardHeader class="pb-3">
                            <CardTitle
                              class="flex items-center gap-3 text-gray-700"
                            >
                              <div
                                class="w-8 h-8 bg-gradient-to-br from-gray-100 to-gray-200 rounded-lg flex items-center justify-center"
                              >
                                <Trophy class="w-4 h-4 text-gray-600"/>
                              </div>
                              {{ t("selection.matchMode") }}
                            </CardTitle>
                            <CardDescription class="text-gray-500">
                              {{ t("selection.matchModeDescription") }}
                            </CardDescription>
                          </CardHeader>
                          <CardContent class="space-y-3">
                            <div
                              :class="`p-4 border rounded-xl cursor-pointer transition-all duration-200 ${
                                matchSettings.mode === 'ranked'
                                  ? 'border-gray-400 bg-gray-50 shadow-sm'
                                  : 'border-gray-200 hover:border-gray-300 hover:bg-gray-25'
                              }`"
                              @click="matchSettings.mode = 'ranked'"
                            >
                              <div class="flex items-start gap-3">
                                <div
                                  class="w-10 h-10 bg-gradient-to-br from-gray-200 to-gray-300 rounded-lg flex items-center justify-center flex-shrink-0"
                                >
                                  <Trophy class="w-5 h-5 text-gray-600"/>
                                </div>
                                <div class="flex-1">
                                  <div class="font-semibold text-gray-800">
                                    {{ t("selection.ranked") }}
                                  </div>
                                  <div class="text-sm text-gray-600 mt-1">
                                    {{ t("selection.rankedDescription") }}
                                  </div>
                                  <div
                                    class="text-xs text-gray-500 mt-2 flex items-center gap-1"
                                  >
                                    <Star class="w-3 h-3"/>
                                    {{ t("selection.highQualityMatching") }}
                                  </div>
                                </div>
                                <div
                                  v-if="matchSettings.mode === 'ranked'"
                                  class="w-5 h-5 bg-gray-600 rounded-full flex items-center justify-center"
                                >
                                  <Check class="w-3 h-3 text-white"/>
                                </div>
                              </div>
                            </div>

                            <div
                              :class="`p-4 border rounded-xl cursor-pointer transition-all duration-200 ${
                                matchSettings.mode === 'casual'
                                  ? 'border-gray-400 bg-gray-50 shadow-sm'
                                  : 'border-gray-200 hover:border-gray-300 hover:bg-gray-25'
                              }`"
                              @click="matchSettings.mode = 'casual'"
                            >
                              <div class="flex items-start gap-3">
                                <div
                                  class="w-10 h-10 bg-gradient-to-br from-gray-200 to-gray-300 rounded-lg flex items-center justify-center flex-shrink-0"
                                >
                                  <Gamepad2 class="w-5 h-5 text-gray-600"/>
                                </div>
                                <div class="flex-1">
                                  <div class="font-semibold text-gray-800">
                                    {{ t("selection.casual") }}
                                  </div>
                                  <div class="text-sm text-gray-600 mt-1">
                                    {{ t("selection.casualDescription") }}
                                  </div>
                                  <div
                                    class="text-xs text-gray-500 mt-2 flex items-center gap-1"
                                  >
                                    <Heart class="w-3 h-3"/>
                                    {{ t("selection.friendlyEnvironment") }}
                                  </div>
                                </div>
                                <div
                                  v-if="matchSettings.mode === 'casual'"
                                  class="w-5 h-5 bg-gray-600 rounded-full flex items-center justify-center"
                                >
                                  <Check class="w-3 h-3 text-white"/>
                                </div>
                              </div>
                            </div>
                          </CardContent>
                        </Card>
                      </div>

                      <!-- Difficulty Preference -->
                      <div
                        class="opacity-100 transform-none transition-all duration-300"
                      >
                        <Card
                          class="h-full bg-white/80 backdrop-blur-sm border border-slate-200 shadow-sm hover:shadow-md transition-all duration-300"
                        >
                          <CardHeader class="pb-3">
                            <CardTitle
                              class="flex items-center gap-3 text-gray-700"
                            >
                              <div
                                class="w-8 h-8 bg-gradient-to-br from-gray-100 to-gray-200 rounded-lg flex items-center justify-center"
                              >
                                <Target class="w-4 h-4 text-gray-600"/>
                              </div>
                              {{ t("selection.difficultyPreference") }}
                            </CardTitle>
                            <CardDescription class="text-gray-500">
                              {{
                                t("selection.difficultyPreferenceDescription")
                              }}
                            </CardDescription>
                          </CardHeader>
                          <CardContent class="space-y-3">
                            <div
                              v-for="difficulty in difficultyOptions"
                              :key="difficulty.id"
                              :class="`p-3 border rounded-xl cursor-pointer transition-all duration-200 ${
                                matchSettings.difficulty === difficulty.id
                                  ? 'border-gray-400 bg-gray-50 shadow-sm'
                                  : 'border-gray-200 hover:border-gray-300 hover:bg-gray-25'
                              }`"
                              @click="matchSettings.difficulty = difficulty.id"
                            >
                              <div class="flex items-center gap-3">
                                <div
                                  :class="`w-8 h-8 bg-gradient-to-br ${difficulty.color} rounded-lg flex items-center justify-center flex-shrink-0`"
                                >
                                  <component
                                    :is="difficulty.icon"
                                    :class="`w-4 h-4 ${difficulty.iconColor}`"
                                  ></component>
                                </div>
                                <div class="flex-1">
                                  <div class="flex items-center gap-2">
                                    <span class="font-semibold text-gray-800">
                                      {{ difficulty.name }}
                                    </span>
                                    <span
                                      class="text-xs px-2 py-0.5 bg-gray-100 text-gray-600 rounded-full"
                                    >
                                      {{ difficulty.tag }}
                                    </span>
                                  </div>
                                  <div class="text-xs text-gray-600 mt-0.5">
                                    {{ difficulty.desc }}
                                  </div>
                                </div>
                                <div
                                  v-if="
                                    matchSettings.difficulty === difficulty.id
                                  "
                                  class="w-5 h-5 bg-gray-600 rounded-full flex items-center justify-center"
                                >
                                  <Check class="w-3 h-3 text-white"/>
                                </div>
                              </div>
                            </div>
                          </CardContent>
                        </Card>
                      </div>

                      <!-- Advanced Settings -->
                      <div
                        class="opacity-100 transform-none transition-all duration-300"
                      >
                        <Card
                          class="h-full bg-white/80 backdrop-blur-sm border border-slate-200 shadow-sm hover:shadow-md transition-all duration-300"
                        >
                          <CardHeader class="pb-3">
                            <CardTitle
                              class="flex items-center gap-3 text-gray-700"
                            >
                              <div
                                class="w-8 h-8 bg-gradient-to-br from-gray-100 to-gray-200 rounded-lg flex items-center justify-center"
                              >
                                <Settings class="w-4 h-4 text-gray-600"/>
                              </div>
                              {{ t("selection.advancedSettings") }}
                            </CardTitle>
                            <CardDescription class="text-gray-500">
                              {{ t("selection.advancedSettingsDescription") }}
                            </CardDescription>
                          </CardHeader>
                          <CardContent class="space-y-4">
                            <!-- Server Region -->
                            <div>
                              <label
                                class="flex items-center gap-2 text-sm font-medium text-gray-700 mb-3"
                              >
                                <Globe class="w-4 h-4 text-gray-500"/>
                                {{ t("selection.serverRegion") }}
                              </label>
                              <div class="space-y-2">
                                <div
                                  v-for="region in regionOptions"
                                  :key="region.id"
                                  :class="`p-2 border rounded-lg cursor-pointer transition-all duration-200 ${
                                    matchSettings.region === region.id
                                      ? 'border-gray-400 bg-gray-50'
                                      : 'border-gray-200 hover:border-gray-300'
                                  }`"
                                  @click="matchSettings.region = region.id"
                                >
                                  <div class="flex items-center gap-2">
                                    <component
                                      :is="region.icon"
                                      class="w-4 h-4 text-gray-500"
                                    ></component>
                                    <span
                                      class="text-sm font-medium text-gray-700"
                                    >
                                      {{ region.name }}
                                    </span>
                                    <span class="text-xs text-gray-500 ml-auto">
                                      {{ region.desc }}
                                    </span>
                                    <Check
                                      v-if="matchSettings.region === region.id"
                                      class="w-4 h-4 text-gray-600 ml-1"
                                    />
                                  </div>
                                </div>
                              </div>
                            </div>

                            <!-- Max Wait Time -->
                            <div>
                              <label
                                class="flex items-center gap-2 text-sm font-medium text-gray-700 mb-3"
                              >
                                <Clock class="w-4 h-4 text-gray-500"/>
                                {{ t("selection.maxWaitTime") }}
                              </label>
                              <div class="space-y-2">
                                <div
                                  v-for="time in waitTimeOptions"
                                  :key="time.id"
                                  :class="`p-2 border rounded-lg cursor-pointer transition-all duration-200 ${
                                    matchSettings.maxWaitTime === time.id
                                      ? 'border-gray-400 bg-gray-50'
                                      : 'border-gray-200 hover:border-gray-300'
                                  }`"
                                  @click="matchSettings.maxWaitTime = time.id"
                                >
                                  <div class="flex items-center gap-2">
                                    <Timer class="w-4 h-4 text-gray-500"/>
                                    <span
                                      class="text-sm font-medium text-gray-700"
                                    >
                                      {{ time.name }}
                                    </span>
                                    <span class="text-xs text-gray-500 ml-auto">
                                      {{ time.desc }}
                                    </span>
                                    <Check
                                      v-if="
                                        matchSettings.maxWaitTime === time.id
                                      "
                                      class="w-4 h-4 text-gray-600 ml-1"
                                    />
                                  </div>
                                </div>
                              </div>
                            </div>
                          </CardContent>
                        </Card>
                      </div>
                    </div>

                    <!-- Start Matching Button -->
                    <div class="text-center">
                      <motion.div
                        :whileHover="{ scale: 1.05 }"
                        :whileTap="{ scale: 0.95 }"
                        class="hover:scale-105 active:scale-95 transition-transform"
                      >
                        <Button
                          class="bg-gradient-to-r from-gray-600 to-gray-700 hover:from-gray-700 hover:to-gray-800 text-white px-8 py-4 h-auto shadow-lg hover:shadow-xl transition-all duration-300"
                          size="lg"
                          @click="isSearching = true"
                        >
                          <Search class="w-5 h-5 mr-2"/>
                          {{ t("selection.startMatching") }}
                        </Button>
                      </motion.div>
                    </div>
                  </div>

                  <Card
                    v-else-if="isSearching"
                    class="bg-white/70 backdrop-blur-sm border-slate-200 shadow-lg"
                  >
                    <CardContent class="p-6 text-center">
                      <div
                        class="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4"
                      >
                        <motion
                          :animate="{ rotate: 360 }"
                          :transition="{
                            duration: 2,
                            repeat: Infinity,
                            ease: 'linear',
                          }"
                        >
                          <Search class="w-8 h-8 text-blue-600"/>
                        </motion>
                      </div>
                      <h3 class="text-xl font-bold mb-2">
                        {{ t("selection.searchingForOpponent") }}
                      </h3>
                      <p class="text-slate-600 mb-4">
                        {{ t("selection.estimatedWaitTime") }}
                      </p>

                      <div class="flex items-center justify-center gap-2 mb-6">
                        <Clock class="w-4 h-4 text-blue-600"/>
                        <span class="text-blue-600 font-mono">
                          {{ Math.floor(searchTime / 60) }}:
                          {{ (searchTime % 60).toString().padStart(2, "0") }}
                        </span>
                      </div>

                      <div class="space-y-3 mb-6">
                        <div class="w-full bg-slate-200 rounded-full h-2">
                          <div
                            :style="`width: ${Math.min(
                              100,
                              (searchTime / 60) * 100
                            )}%`"
                            class="bg-blue-600 h-2 rounded-full transition-all duration-300"
                          ></div>
                        </div>
                        <p class="text-xs text-slate-500">
                          {{ t("selection.matchingSystemNote") }}
                        </p>
                      </div>

                      <Button variant="outline" @click="cancelSearch">
                        {{ t("selection.cancelMatching") }}
                      </Button>
                    </CardContent>
                  </Card>

                  <Card
                    v-else
                    class="bg-gradient-to-r from-yellow-50 to-orange-50 border-yellow-200"
                  >
                    <CardContent class="p-6 text-center">
                      <div class="text-4xl mb-4">🎉</div>
                      <h3 class="text-xl font-bold mb-2">
                        {{ t("selection.opponentFound") }}
                      </h3>
                      <p class="text-slate-600 mb-6">
                        {{ t("selection.prepareForBattle") }}
                      </p>

                      <div class="flex items-center justify-center gap-8 mb-6">
                        <div class="text-center">
                          <div
                            class="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-2"
                          >
                            <span class="text-xl">🦅</span>
                          </div>
                          <p class="font-semibold">{{ t("selection.you") }}</p>
                          <p class="text-sm text-slate-500">
                            {{ t("selection.level", {level: 42}) }}
                          </p>
                        </div>

                        <div class="text-2xl font-bold text-slate-400">VS</div>

                        <div class="text-center">
                          <div
                            class="w-12 h-12 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-2"
                          >
                            <span class="text-xl">⚡</span>
                          </div>
                          <p class="font-semibold">
                            {{ t("selection.aiNemesis") }}
                          </p>
                          <p class="text-sm text-slate-500">
                            {{ t("selection.level", {level: 42}) }}
                          </p>
                        </div>
                      </div>

                      <Button
                        class="bg-gradient-to-r from-green-600 to-emerald-600"
                        size="lg"
                        @click="startBattle"
                      >
                        <Play class="w-5 h-5 mr-2"/>
                        {{ t("selection.startBattle") }}
                      </Button>
                    </CardContent>
                  </Card>
                </div>

                <!-- 房间对战模式 -->
                <div v-if="pvpMode === 'rooms'" class="space-y-6">
                  <div class="flex items-center justify-between">
                    <h3 class="text-lg font-semibold">
                      {{ t("selection.battleRooms") }}
                    </h3>
                    <Button
                      class="bg-gradient-to-r from-blue-600 to-purple-600"
                      @click="showCreateRoom = true"
                    >
                      <Plus class="w-4 h-4 mr-2"/>
                      创建房间
                    </Button>
                  </div>

                  <div class="grid gap-4">
                    <Card
                      v-for="room in mockBattleRooms"
                      :key="room.id"
                      class="bg-white/70 backdrop-blur-sm border-slate-200 shadow-lg"
                    >
                      <CardContent class="p-4">
                        <div class="flex items-center justify-between">
                          <div class="flex items-center gap-4">
                            <div
                              class="w-12 h-12 bg-gradient-to-br from-blue-500 to-purple-500 rounded-lg flex items-center justify-center"
                            >
                              <Lock
                                v-if="room.isPrivate"
                                class="w-6 h-6 text-white"
                              />
                              <Globe v-else class="w-6 h-6 text-white"/>
                            </div>
                            <div>
                              <div class="flex items-center gap-2 mb-1">
                                <h4 class="font-semibold">
                                  {{ room.name }}
                                </h4>
                                <Badge
                                  :variant="
                                    room.mode === 'ranked'
                                      ? 'default'
                                      : 'secondary'
                                  "
                                  class="text-xs"
                                >
                                  {{
                                    room.mode === "ranked"
                                      ? t("selection.ranked")
                                      : room.mode === "casual"
                                        ? t("selection.casual")
                                        : t("selection.private")
                                  }}
                                </Badge>
                                <Badge
                                  :variant="
                                    room.status === 'waiting'
                                      ? 'outline'
                                      : room.status === 'in-progress'
                                      ? 'default'
                                      : 'secondary'
                                  "
                                  class="text-xs"
                                >
                                  {{
                                    room.status === "waiting"
                                      ? "等待中"
                                      : room.status === "in-progress"
                                        ? "进行中"
                                        : "已结束"
                                  }}
                                </Badge>
                              </div>
                              <div
                                class="flex items-center gap-4 text-sm text-slate-500"
                              >
                                <span class="flex items-center gap-1">
                                  <Users class="w-3 h-3"/>
                                  {{ room.currentPlayers }}/{{
                                    room.maxPlayers
                                  }}
                                </span>
                                <span class="flex items-center gap-1">
                                  <Eye class="w-3 h-3"/>
                                  {{ room.spectators.length }}
                                </span>
                                <span class="flex items-center gap-1">
                                  <Timer class="w-3 h-3"/>
                                  {{ room.settings.timePerRound }}s/题
                                </span>
                                <span class="flex items-center gap-1">
                                  <Target class="w-3 h-3"/>
                                  {{
                                    getDifficultyText(room.settings.difficulty)
                                  }}
                                </span>
                              </div>
                            </div>
                          </div>
                          <div class="flex items-center gap-2">
                            <Button
                              v-if="
                                room.status === 'waiting' &&
                                room.currentPlayers < room.maxPlayers
                              "
                              class="bg-green-600 hover:bg-green-700"
                              size="sm"
                            >
                              <Play class="w-3 h-3 mr-1"/>
                              加入
                            </Button>
                            <Button
                              v-if="
                                room.status === 'in-progress' &&
                                room.settings.allowSpectators
                              "
                              size="sm"
                              variant="outline"
                            >
                              <Eye class="w-3 h-3 mr-1"/>
                              观战
                            </Button>
                            <Button size="sm" variant="ghost">
                              <MoreHorizontal class="w-3 h-3"/>
                            </Button>
                          </div>
                        </div>

                        <div
                          v-if="room.players.length > 0"
                          class="mt-3 pt-3 border-t border-slate-200"
                        >
                          <div class="flex items-center gap-2">
                            <span class="text-xs text-slate-500"> 玩家： </span>
                            <div
                              v-for="(player, index) in room.players"
                              :key="player.id"
                              class="flex items-center gap-1"
                            >
                              <span class="text-lg">
                                {{ player.avatar }}
                              </span>
                              <span class="text-sm font-medium">
                                {{ player.name }}
                              </span>
                              <span v-if="player.badge" class="text-xs">
                                {{ player.badge }}
                              </span>
                              <span
                                v-if="index < room.players.length - 1"
                                class="text-slate-300 mx-1"
                              >
                                |
                              </span>
                            </div>
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  </div>
                </div>

                <!-- 好友对战模式 -->
                <div v-if="pvpMode === 'friends'" class="space-y-6">
                  <div class="flex items-center justify-between">
                    <h3 class="text-lg font-semibold">好友列表</h3>
                    <Button variant="outline">
                      <UserPlus class="w-4 h-4 mr-2"/>
                      添加好友
                    </Button>
                  </div>

                  <div class="grid gap-4">
                    <Card
                      v-for="friend in mockFriends"
                      :key="friend.id"
                      class="bg-white/70 backdrop-blur-sm border-slate-200 shadow-lg"
                    >
                      <CardContent class="p-4">
                        <div class="flex items-center justify-between">
                          <div class="flex items-center gap-4">
                            <div class="relative">
                              <div
                                class="w-12 h-12 bg-gradient-to-br from-purple-500 to-pink-500 rounded-full flex items-center justify-center"
                              >
                                <span class="text-2xl">
                                  {{ friend.avatar }}
                                </span>
                              </div>
                              <div
                                :class="`absolute -bottom-1 -right-1 w-4 h-4 ${
                                  friend.isOnline
                                    ? 'bg-green-500'
                                    : 'bg-slate-400'
                                } rounded-full border-2 border-white flex items-center justify-center`"
                              >
                                <WifiOff class="w-2 h-2 text-white"/>
                              </div>
                            </div>
                            <div>
                              <div class="flex items-center gap-2 mb-1">
                                <h4 class="font-semibold">
                                  {{ friend.name }}
                                </h4>
                                <Badge class="text-xs" variant="outline">
                                  Lv.{{ friend.level }}
                                </Badge>
                                <Badge
                                  v-if="friend.mutualFriends"
                                  class="text-xs"
                                  variant="secondary"
                                >
                                  {{ friend.mutualFriends }}个共同好友
                                </Badge>
                              </div>
                              <div class="flex items-center gap-2 text-sm">
                                <span
                                  :class="
                                    friend.isOnline
                                      ? 'text-green-600'
                                      : 'text-slate-500'
                                  "
                                >
                                  {{ friend.status }}
                                </span>
                                <span
                                  v-if="!friend.isOnline && friend.lastSeen"
                                  class="text-slate-400 text-xs"
                                >
                                  最后在线：{{ formatDate(friend.lastSeen) }}
                                </span>
                              </div>
                            </div>
                          </div>
                          <div class="flex items-center gap-2">
                            <Button
                              v-if="friend.isOnline"
                              class="bg-green-600 hover:bg-green-700"
                              size="sm"
                            >
                              <Swords class="w-3 h-3 mr-1"/>
                              邀请对战
                            </Button>
                            <Button v-else disabled size="sm" variant="outline">
                              <MessageCircle class="w-3 h-3 mr-1"/>
                              发送消息
                            </Button>
                            <Button size="sm" variant="ghost">
                              <MoreHorizontal class="w-3 h-3"/>
                            </Button>
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  </div>
                </div>
              </div>
            </TabsContent>

            <!-- Leaderboard Tab -->
            <TabsContent class="space-y-6" value="leaderboard">
              <div class="grid lg:grid-cols-3 gap-6">
                <!-- 当前赛季信息 -->
                <Card
                  class="bg-gradient-to-br from-yellow-50 to-orange-50 border-yellow-200"
                >
                  <CardHeader>
                    <CardTitle class="flex items-center gap-2">
                      <Calendar class="w-5 h-5 text-yellow-600"/>
                      当前赛季
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div class="space-y-3">
                      <div>
                        <h3 class="font-semibold text-lg">赛季一：觉醒</h3>
                        <p class="text-sm text-slate-600">
                          2024年8月 - 2024年11月
                        </p>
                      </div>
                      <div class="space-y-2">
                        <div class="flex justify-between text-sm">
                          <span>赛季进度</span>
                          <span>75%</span>
                        </div>
                        <div class="w-full bg-slate-200 rounded-full h-2">
                          <div
                            class="bg-yellow-500 h-2 rounded-full"
                            style="width: 75%"
                          ></div>
                        </div>
                      </div>
                      <div class="pt-2">
                        <h4 class="font-medium mb-2">赛季奖励</h4>
                        <div class="space-y-1 text-sm">
                          <div class="flex items-center gap-2">
                            <Crown class="w-4 h-4 text-yellow-500"/>
                            <span>王者：专属头衔 + 500积分</span>
                          </div>
                          <div class="flex items-center gap-2">
                            <Star class="w-4 h-4 text-blue-500"/>
                            <span>大师：专属徽章 + 300积分</span>
                          </div>
                          <div class="flex items-center gap-2">
                            <Medal class="w-4 h-4 text-purple-500"/>
                            <span>钻石：纪念徽章 + 200积分</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </CardContent>
                </Card>

                <!-- 你的排名 -->
                <Card
                  class="bg-gradient-to-br from-blue-50 to-indigo-50 border-blue-200"
                >
                  <CardHeader>
                    <CardTitle class="flex items-center gap-2">
                      <TrendingUp class="w-5 h-5 text-blue-600"/>
                      你的排名
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div class="space-y-4">
                      <div class="text-center">
                        <div class="text-3xl font-bold text-blue-600">#42</div>
                        <p class="text-sm text-slate-600">当前排名</p>
                      </div>
                      <div class="space-y-2">
                        <div class="flex justify-between text-sm">
                          <span>积分</span>
                          <span class="font-medium">1,850</span>
                        </div>
                        <div class="flex justify-between text-sm">
                          <span>胜率</span>
                          <span class="font-medium text-green-600"> 68% </span>
                        </div>
                        <div class="flex justify-between text-sm">
                          <span>连胜</span>
                          <span class="font-medium text-orange-600"> 5 </span>
                        </div>
                      </div>
                      <div class="pt-2">
                        <Badge
                          class="w-full justify-center bg-blue-100 text-blue-700 border-blue-300"
                          variant="outline"
                        >
                          🏅 铂金勇士
                        </Badge>
                      </div>
                    </div>
                  </CardContent>
                </Card>

                <!-- 最近战绩 -->
                <Card
                  class="bg-gradient-to-br from-green-50 to-emerald-50 border-green-200"
                >
                  <CardHeader>
                    <CardTitle class="flex items-center gap-2">
                      <Gamepad2 class="w-5 h-5 text-green-600"/>
                      最近战绩
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div class="space-y-3">
                      <div
                        v-for="(match, index) in recentMatches"
                        :key="index"
                        class="flex items-center justify-between text-sm"
                      >
                        <div class="flex items-center gap-2">
                          <Badge
                            :variant="
                              match.result === 'W' ? 'default' : 'destructive'
                            "
                            class="w-6 h-6 p-0 flex items-center justify-center"
                          >
                            {{ match.result }}
                          </Badge>
                          <span>{{ match.opponent }}</span>
                        </div>
                        <span class="text-slate-600">
                          {{ match.score }}
                        </span>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </div>

              <!-- 排行榜 -->
              <Card
                class="bg-white/70 backdrop-blur-sm border-slate-200 shadow-lg"
              >
                <CardHeader>
                  <CardTitle class="flex items-center gap-2">
                    <Trophy class="w-5 h-5 text-yellow-600"/>
                    全球排行榜
                  </CardTitle>
                  <CardDescription>当前赛季顶级玩家排名</CardDescription>
                </CardHeader>
                <CardContent>
                  <div class="space-y-4">
                    <div
                      v-for="(player, index) in mockLeaderboard"
                      :key="player.playerId"
                      :class="
                        index < 3
                          ? 'bg-gradient-to-r from-yellow-50 to-orange-50 border border-yellow-200'
                          : 'bg-slate-50'
                      "
                      class="flex items-center gap-4 p-4 rounded-lg transition-all duration-200"
                    >
                      <div
                        :class="
                          index === 0
                            ? 'bg-yellow-500 text-white'
                            : index === 1
                            ? 'bg-gray-400 text-white'
                            : index === 2
                            ? 'bg-amber-600 text-white'
                            : 'bg-slate-300 text-slate-700'
                        "
                        class="w-8 h-8 rounded-full flex items-center justify-center font-bold text-sm"
                      >
                        {{ player.rank }}
                      </div>

                      <div class="flex-1">
                        <div class="flex items-center gap-2 mb-1">
                          <h3 class="font-semibold">
                            {{ player.playerName }}
                          </h3>
                          <span v-if="player.badge" class="text-lg">{{
                              player.badge
                            }}</span>
                          <Badge
                            v-if="player.title"
                            class="text-xs"
                            variant="outline"
                          >
                            {{ player.title }}
                          </Badge>
                        </div>
                        <div
                          class="flex items-center gap-4 text-sm text-slate-600"
                        >
                          <span>积分: {{ player.rankPoints }}</span>
                          <span>胜率: {{ player.winRate }}%</span>
                          <span>连胜: {{ player.currentStreak }}</span>
                        </div>
                      </div>

                      <div class="text-right">
                        <div class="font-semibold text-lg">
                          {{ player.wins }}-{{ player.losses }}-{{
                            player.draws
                          }}
                        </div>
                        <div class="text-sm text-slate-500">胜-负-平</div>
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </TabsContent>
          </Tabs>
        </motion.div>
      </div>
    </div>

    <div
      v-if="phase === 'battle'"
      class="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50/30 to-indigo-50"
    >
      <div class="container mx-auto px-4 py-8">
        <div class="opacity-100 transition-all duration-500">
          <!-- 对战页面顶部返回区域 -->
          <div class="flex items-center justify-between mb-6">
            <div class="hover:scale-102 active:scale-98 transition-transform">
              <Button
                class="flex items-center gap-2 text-slate-600 hover:text-slate-800 hover:bg-slate-100 transition-all duration-200"
                variant="ghost"
                @click="onBack"
              >
                <ArrowLeft class="w-4 h-4"/>
                {{ t('battle.backToLobby') }}
              </Button>
            </div>

            <div class="flex items-center gap-2">
              <Badge class="px-3 py-1" variant="outline">
                {{
                  pvpMode === "battle"
                    ? t('battle.pvpBattle')
                    : battleMode === "team"
                      ? t('battle.teamMode')
                      : t('battle.soloBattle')
                }}
              </Badge>
              <Badge
                class="px-3 py-1 bg-blue-50 text-blue-600 border-blue-200"
                variant="outline"
              >
                <!--                第 {{ currentStats.round }} / {{ totalRounds }} 轮-->
                {{
                  t('battle.round', {
                    current: currentStats.round,
                    total: totalRounds
                  })
                }}1111
              </Badge>
            </div>
          </div>

          <!-- 优化后的战斗状态栏 -->
          <div class="grid grid-cols-3 gap-6 mb-8">
            <!-- 玩家状态 -->
            <Card
              class="bg-white/80 backdrop-blur-sm border-blue-200 shadow-lg"
            >
              <CardContent class="p-4">
                <div class="flex items-center gap-3 mb-3">
                  <div
                    class="w-10 h-10 bg-gradient-to-br from-blue-500 to-blue-600 rounded-full flex items-center justify-center shadow-md"
                  >
                    <UserCheck
                      v-if="pvpMode === 'battle'"
                      class="w-6 h-6 text-white"
                    />
                    <Users
                      v-else-if="pvpMode === 'team'"
                      class="w-6 h-6 text-white"
                    />
                    <Gamepad2 v-else class="w-6 h-6 text-white"/>
                  </div>
                  <div>
                    <h3 class="font-semibold text-blue-700">
                      {{
                        pvpMode === "battle"
                          ? t('battle.you')
                          : battleMode === "team"
                            ? t('battle.yourTeam')
                            : t('battle.player')
                      }}
                    </h3>
                    <p class="text-sm text-slate-500">
                      {{
                        pvpMode === "battle"
                          ? "🦅 等级42"
                          : battleMode === "team"
                            ? `${selectedTeamSize}人团队`
                            : t('battle.you')
                      }}
                    </p>
                  </div>
                </div>
                <div class="space-y-2">
                  <div class="flex justify-between text-sm">
                    <span>{{ t('battle.score') }}</span>
                    <span class="font-bold text-blue-600">
                      {{
                        pvpMode === "battle"
                          ? currentStats.player1Score
                          : battleMode === "team"
                            ? currentStats.playerTeamScore
                            : currentStats.playerScore
                      }}
                    </span>
                  </div>
                  <div class="flex justify-between text-sm">
                    <span>{{ t('battle.correct') }}</span>
                    <span class="font-medium">
                      {{
                        pvpMode === "battle"
                          ? currentStats.player1Correct
                          : battleMode === "team"
                            ? currentStats.playerTeamCorrect
                            : currentStats.playerCorrect
                      }}
                      /{{ currentStats.round - 1 }}
                    </span>
                  </div>
                  <!--                  <div class="w-full bg-blue-100 rounded-full h-2">-->
                  <!--                    <div-->
                  <!--                      :style="`width: ${calculatePlayerProgress()}%`"-->
                  <!--                      class="bg-blue-500 h-2 rounded-full transition-all duration-300"-->
                  <!--                    ></div>-->
                  <!--                  </div>-->
                  <Progress
                    :model-value="
                      pvpMode === 'battle'
                        ? (currentStats.player1Correct / totalRounds) * 100
                        : battleMode === 'team'
                        ? (currentStats.playerTeamCorrect / totalRounds) * 100
                        : (currentStats.playerCorrect / totalRounds) * 100
                    "
                    class="h-2 bg-blue-100"
                  />
                </div>
              </CardContent>
            </Card>

            <!-- 时间和回合 -->
            <Card
              class="bg-white/80 backdrop-blur-sm border-slate-200 shadow-lg"
            >
              <CardContent class="p-4 text-center">
                <div class="mb-3">
                  <div
                    :class="
                      timeRemaining <= 5
                        ? 'animate-pulse text-red-500'
                        : 'text-yellow-500'
                    "
                    class="w-8 h-8 mx-auto mb-2 transition-all"
                  >
                    <Timer class="w-8 h-8" name="mdi:timer"/>
                  </div>
                  <div
                    :class="`text-2xl font-bold ${
                      timeRemaining <= 5 ? 'text-red-600' : 'text-slate-700'
                    }`"
                  >
                    {{ currentStats.timeRemaining }}
                  </div>
                  <p class="text-sm text-slate-500">{{ t('battle.seconds') }}</p>
                </div>
                <div class="text-sm">
                  第 {{ currentStats.round }} / {{ totalRounds }} 回合

                </div>
                <div class="w-full bg-gray-200 rounded-full h-2 mt-2">
                  <div
                    :style="`width: ${
                      ((currentStats.round - 1) / totalRounds) * 100
                    }%`"
                    class="bg-gray-600 h-2 rounded-full transition-all duration-300"
                  ></div>
                </div>
              </CardContent>
            </Card>

            <!-- 对手状态 -->
            <Card class="bg-white/80 backdrop-blur-sm border-red-200 shadow-lg">
              <CardContent class="p-4">
                <div class="flex items-center gap-3 mb-3">
                  <div class="relative text-2xl">
                    {{
                      pvpMode === "battle"
                        ? opponent?.avatar
                        : selectedAI?.emoji
                    }}
                    <!-- AI状态指示器 -->
                    <div
                      v-if="pvpMode !== 'battle'"
                      class="absolute -bottom-1 -right-1"
                    >
                      <div
                        v-if="aiStatus === 'thinking'"
                        class="w-4 h-4 bg-blue-500 rounded-full border-2 border-white flex items-center justify-center animate-pulse"
                      >
                        <div
                          class="w-2 h-2 border border-white border-t-transparent rounded-full animate-spin"
                        ></div>
                      </div>
                      <div
                        v-else-if="aiStatus === 'answering'"
                        class="w-4 h-4 bg-orange-500 rounded-full border-2 border-white flex items-center justify-center"
                      >
                        <Zap
                          class="w-2 h-2 text-white"
                          name="mdi:lightning-bolt"
                        />
                      </div>
                      <div
                        v-else-if="aiStatus === 'completed'"
                        class="w-4 h-4 bg-green-500 rounded-full border-2 border-white flex items-center justify-center"
                      >
                        <Check class="w-2 h-2 text-white" name="mdi:check"/>
                      </div>
                    </div>
                  </div>
                  <div class="flex-1">
                    <h3 class="font-semibold text-red-700">
                      {{
                        pvpMode === "battle"
                          ? opponent?.name
                          : battleMode === "team"
                            ? `${selectedAI?.name}团队`
                            : selectedAI?.name
                      }}
                    </h3>
                    <div class="flex items-center gap-2">
                      <p class="text-sm text-slate-500">
                        {{
                          pvpMode === "battle"
                            ? `等级 ${opponent?.level}`
                            : battleMode === "team"
                              ? `AI ${selectedTeamSize}人团队`
                              : t('battle.aiOpponent')
                        }}
                      </p>
                      <!-- AI状态文本 -->
                      <span
                        v-if="pvpMode !== 'battle'"
                        :class="{
                          'bg-blue-500': aiStatus === 'thinking',
                          'bg-orange-500': aiStatus === 'answering',
                          'bg-green-500': aiStatus === 'completed',
                          'bg-gray-500': aiStatus === 'waiting',
                        }"
                        class="text-xs px-2 py-0.5 rounded-full font-medium text-white transition-all duration-300"
                      >
                        {{ getAIStatusText(aiStatus) }}
                      </span>
                    </div>
                  </div>
                </div>

                <!-- AI状态信息区域 - 固定高度避免布局抖动 -->
                <div
                  v-if="pvpMode !== 'battle'"
                  class="mb-3 h-16 flex flex-col justify-center"
                >
                  <!-- AI思考进度条 -->
                  <div v-if="aiStatus === 'thinking'">
                    <div
                      class="flex justify-between text-xs text-slate-500 mb-1"
                    >
                      <span>{{ t('battle.aiThinking') }}</span>
                      <span>{{ Math.round(aiThinkingProgress) }}%</span>
                    </div>
                    <div class="w-full bg-slate-200 rounded-full h-2">
                      <div
                        :style="`width: ${aiThinkingProgress}%`"
                        class="bg-gradient-to-r from-blue-500 to-blue-600 h-2 rounded-full transition-all duration-100"
                      ></div>
                    </div>
                  </div>

                  <!-- AI答题时间显示 -->
                  <div
                    v-else-if="aiAnswerTime && aiStatus === 'completed'"
                    class="p-2 bg-green-50 rounded-lg border border-green-200"
                  >
                    <div class="flex items-center justify-between text-sm">
                      <span class="text-green-700 font-medium">
<!--                        AI答题用时-->
                        {{ t('battle.aiResponseTime') }}
                      </span>
                      <span class="text-green-600 font-mono">
                        {{ aiAnswerTime.toFixed(2) }} {{ t('battle.seconds') }}
                      </span>
                    </div>
                  </div>

                  <!-- 等待和答题状态的占位区域 -->
                  <div
                    v-else-if="
                      aiStatus === 'waiting' || aiStatus === 'answering'
                    "
                    class="flex items-center justify-center h-full"
                  >
                    <div class="text-xs text-slate-400 text-center">
                      {{
                        aiStatus === "waiting" ? t('battle.waitingToStart') : t('battle.answering')
                      }}
                    </div>
                  </div>
                </div>

                <div class="space-y-2">
                  <div class="flex justify-between text-sm">
                    <span>{{ t('battle.score') }}</span>
                    <span class="font-bold text-red-600">
                      {{
                        pvpMode === "battle"
                          ? currentStats.player2Score
                          : battleMode === "team"
                            ? currentStats.aiTeamScore
                            : currentStats.aiScore
                      }}
                    </span>
                  </div>
                  <div class="flex justify-between text-sm">
                    <span>{{ t('battle.correct') }}</span>
                    <span class="font-medium">
                      {{
                        pvpMode === "battle"
                          ? currentStats.player2Correct
                          : battleMode === "team"
                            ? currentStats.aiTeamCorrect
                            : currentStats.aiCorrect
                      }}
                      /{{ currentStats.round - 1 }}
                    </span>
                  </div>
                  <!--                  <div class="w-full bg-red-100 rounded-full h-2">-->
                  <!--                    <div-->
                  <!--                      :style="`width: ${calculateAIProgress()}%`"-->
                  <!--                      class="bg-red-500 h-2 rounded-full transition-all duration-300"-->
                  <!--                    ></div>-->
                  <!--                  </div>-->
                  <Progress
                    :model-value="
                      pvpMode === 'battle'
                        ? (currentStats.player1Correct / totalRounds) * 100
                        : battleMode === 'team'
                        ? (currentStats.playerTeamCorrect / totalRounds) * 100
                        : (currentStats.playerCorrect / totalRounds) * 100
                    "
                    class="h-2 bg-blue-100"
                  />
                </div>
              </CardContent>
            </Card>
          </div>

          <!-- 优化后的挑战区域 -->
          <Card
            v-if="currentChallenge"
            class="bg-white/90 backdrop-blur-sm border-slate-200 shadow-xl mb-6"
          >
            <CardContent class="p-8">
              <div class="text-center space-y-6">
                <div class="flex items-center justify-center gap-3 mb-4">
                  <Badge class="px-3 py-1" variant="outline">
                    {{
                      pvpMode === "battle"
                        ? t('battle.pvpBattle')
                        : battleMode === "team"
                          ? t('battle.teamChallenge')
                          : t('battle.soloChallenge')
                    }}
                  </Badge>
                  <Badge
                    class="px-3 py-1 bg-slate-100 text-slate-600"
                    variant="outline"
                  >
                    {{ currentChallenge.category }}
                  </Badge>
                  <Badge
                    :class="`px-3 py-1 ${
                      currentChallenge.difficulty === 'easy'
                        ? 'bg-green-50 text-green-600 border-green-200'
                        : currentChallenge.difficulty === 'medium'
                        ? 'bg-yellow-50 text-yellow-600 border-yellow-200'
                        : 'bg-red-50 text-red-600 border-red-200'
                    }`"
                    variant="outline"
                  >
                    {{ getDifficultyText(currentChallenge.difficulty) }}
                  </Badge>
                  <Badge
                    v-if="pvpMode === 'battle'"
                    class="px-3 py-1 bg-green-50 text-green-600 border-green-200"
                    variant="outline"
                  >
                    <Wifi class="w-3 h-3 mr-1" name="mdi:wifi"/>
                    实时对战
                  </Badge>
                </div>

                <h2 class="text-2xl font-bold text-slate-800">
                  {{ currentChallenge.question }}
                </h2>

                <!-- 反应测试 -->
                <div
                  v-if="
                    currentChallenge.type === 'reaction' &&
                    !currentChallenge.completed
                  "
                  class="space-y-4"
                >
                  <div
                    v-if="reactionStartTime"
                    class="w-32 h-32 bg-gradient-to-br from-green-400 to-green-500 rounded-full mx-auto cursor-pointer flex items-center justify-center shadow-lg hover:shadow-xl transition-all duration-200 hover:scale-105 active:scale-95"
                    @click="handleAnswer('click')"
                  >
                    <span class="text-2xl font-bold text-white"> 点击! </span>
                  </div>
                  <div
                    v-else
                    class="w-32 h-32 bg-gradient-to-br from-slate-400 to-slate-500 rounded-full mx-auto flex items-center justify-center shadow-lg"
                  >
                    <span class="text-xl text-white"> 等待... </span>
                  </div>
                </div>

                <!-- 选择题 -->
                <div
                  v-if="
                    currentChallenge.options &&
                    currentChallenge.type !== 'reaction' &&
                    !currentChallenge.completed
                  "
                  class="mt-6"
                >
                  <p class="text-sm text-slate-600 mb-3">选择答案：</p>
                  <div class="grid grid-cols-2 gap-3">
                    <div
                      v-for="(option, index) in currentChallenge.options"
                      :key="`${currentChallenge.id}-${option}-${index}`"
                      class="hover:scale-102 active:scale-98 transition-transform"
                    >
                      <Button
                        class="w-full h-12 text-left justify-start bg-white hover:bg-blue-50 hover:border-blue-300 border-slate-200"
                        size="lg"
                        variant="outline"
                        @click="handleAnswer(option)"
                      >
                        <span
                          class="w-6 h-6 rounded-full bg-slate-100 flex items-center justify-center text-xs mr-3 flex-shrink-0"
                        >
                          {{ String.fromCharCode(65 + index) }}
                        </span>
                        <span class="truncate">{{ option }}</span>
                      </Button>
                    </div>
                  </div>
                </div>

                <!-- 数学题输入 -->
                <div
                  v-if="
                    currentChallenge.type === 'math' &&
                    !currentChallenge.options &&
                    !currentChallenge.completed
                  "
                  class="space-y-4"
                >
                  <div class="grid grid-cols-5 gap-3 max-w-md mx-auto">
                    <div
                      v-for="i in 10"
                      :key="i"
                      class="hover:scale-105 active:scale-95 transition-transform"
                    >
                      <Button
                        class="h-12 bg-white hover:bg-blue-50 border-2 hover:border-blue-300"
                        size="lg"
                        variant="outline"
                        @click="handleAnswer(i)"
                      >
                        {{ i }}
                      </Button>
                    </div>
                  </div>
                </div>

                <!-- 答题结果显示 -->
                <div
                  v-if="currentChallenge.completed"
                  class="grid md:grid-cols-2 gap-6 mt-8"
                >
                  <div class="text-center">
                    <h3
                      class="text-lg font-semibold mb-3 flex items-center justify-center gap-2"
                    >
                      <span class="text-xl">🦅</span>
                      {{
                        pvpMode === "battle"
                          ? "你的答案"
                          : battleMode === "team"
                            ? "你的团队"
                            : "你的答案"
                      }}
                    </h3>
                    <div
                      :class="`text-2xl p-4 rounded-lg shadow-md ${
                        currentChallenge.playerAnswer ===
                        currentChallenge.correctAnswer
                          ? 'bg-green-100 text-green-700 border-2 border-green-300'
                          : 'bg-red-100 text-red-700 border-2 border-red-300'
                      }`"
                    >
                      {{
                        currentChallenge.playerAnswer === "timeout"
                          ? "超时"
                          : String(currentChallenge.playerAnswer)
                      }}
                      <Check
                        v-if="
                          currentChallenge.playerAnswer ===
                          currentChallenge.correctAnswer
                        "
                        class="w-6 h-6 inline ml-2"
                      />
                      <X v-else class="w-6 h-6 inline ml-2"/>
                    </div>
                    <p
                      v-if="currentChallenge.timeToAnswer"
                      class="text-sm text-slate-500 mt-2"
                    >
                      用时: {{ currentChallenge.timeToAnswer.toFixed(2) }}秒
                    </p>
                  </div>

                  <div class="text-center">
                    <h3
                      class="text-lg font-semibold mb-3 flex items-center justify-center gap-2"
                    >
                      <span class="text-xl">
                        {{
                          pvpMode === "battle"
                            ? opponent?.avatar
                            : selectedAI?.emoji
                        }}
                      </span>
                      {{
                        pvpMode === "battle"
                          ? `${opponent?.name}的答案`
                          : battleMode === "team"
                            ? "AI团队答案"
                            : "AI答案"
                      }}
                    </h3>

                    <div
                      :class="`text-2xl p-4 rounded-lg shadow-md ${
                        showAIAnswer &&
                        currentChallenge.aiAnswer ===
                          currentChallenge.correctAnswer
                          ? 'bg-green-100 text-green-700 border-2 border-green-300'
                          : showAIAnswer &&
                            currentChallenge.aiAnswer !==
                              currentChallenge.correctAnswer
                          ? 'bg-red-100 text-red-700 border-2 border-red-300'
                          : 'bg-gray-100 text-gray-700 border-2 border-gray-300'
                      }`"
                    >
                      {{
                        showAIAnswer
                          ? String(currentChallenge.aiAnswer)
                          : pvpMode === "battle"
                            ? "答题中..."
                            : aiStatus === "thinking"
                              ? "思考中..."
                              : aiStatus === "answering"
                                ? "答题中..."
                                : "准备中..."
                      }}
                      <Check
                        v-if="
                          showAIAnswer &&
                          currentChallenge.aiAnswer !== undefined &&
                          currentChallenge.aiAnswer ===
                            currentChallenge.correctAnswer
                        "
                        class="w-6 h-6 inline ml-2"
                      />
                      <X
                        v-if="
                          showAIAnswer &&
                          currentChallenge.aiAnswer !== undefined &&
                          currentChallenge.aiAnswer !==
                            currentChallenge.correctAnswer
                        "
                        class="w-6 h-6 inline ml-2"
                      />
                    </div>

                    <!-- AI答题详情 -->
                    <div
                      v-if="
                        pvpMode !== 'battle' && showAIAnswer && aiAnswerTime
                      "
                      class="mt-3 space-y-1"
                    >
                      <p class="text-sm text-slate-500">
                        AI用时: {{ aiAnswerTime.toFixed(2) }}秒
                      </p>
                      <div
                        class="flex items-center justify-center gap-2 text-xs"
                      >
                        <span
                          class="px-2 py-1 bg-slate-100 rounded-full text-slate-600"
                        >
                          {{ selectedAI?.personality?.split("，")[0] }}
                        </span>
                        <span
                          class="px-2 py-1 bg-slate-100 rounded-full text-slate-600"
                        >
                          难度:
                          {{
                            Math.round((selectedAI?.difficulty || 0.5) * 100)
                          }}%
                        </span>
                      </div>
                    </div>

                    <p
                      v-if="pvpMode === 'battle' && showAIAnswer"
                      class="text-sm text-slate-500 mt-2"
                    >
                      实时对战结果
                    </p>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
    <div v-if="phase === 'result'">
      <div
        class="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50"
      >
        <div class="container mx-auto px-4 py-8">
          <!--  结果页面顶部返回区域 -->
          <div class="flex items-center justify-between mb-6">
            <motion.div>
              <Button
                class="flex items-center gap-2 text-slate-600 hover:text-slate-800 hover:bg-slate-100 transition-all duration-200"
                variant="ghost"
                @click="onBack"
              >
                <ArrowLeft class="w-4 h-4"/>
                返回对战大厅
              </Button>
            </motion.div>
            <div class="flex items-center gap-2">
              <Badge class="px-3 py-1" variant="outline">
                {{
                  pvpMode === "battle"
                    ? "真人对战"
                    : battleMode === "team"
                      ? "团队模式"
                      : "单人对战"
                }}
              </Badge>
              <Badge
                :class="{
                  'badge-victory': battleResult === 'victory',
                  'badge-defeat': battleResult === 'defeat',
                  'badge-draw': !['victory', 'defeat'].includes(battleResult),
                }"
                variant="outline"
              >
                {{
                  battleResult === "victory"
                    ? "胜利"
                    : battleResult === "defeat"
                      ? "败北"
                      : "平局"
                }}
              </Badge>
            </div>
          </div>

          <motion.div
            :animate="{ opacity: 1, scale: 1 }"
            :initial="{ opacity: 0, scale: 0.9 }"
            :transition="{ duration: 0.6 }"
            class="text-center"
          >
            <Card
              class="max-w-2xl mx-auto bg-white/90 backdrop-blur-sm shadow-xl"
            >
              <CardContent class="p-8">
                <motion.div
                  :animate="{ scale: [1, 1.1, 1] }"
                  :transition="{ duration: 2, repeat: Infinity }"
                  class="text-6xl mb-4"
                >
                  {{
                    battleResult === "victory"
                      ? "🏆"
                      : battleResult === "defeat"
                        ? "💀"
                        : "🤝"
                  }}
                </motion.div>

                <h2
                  :class="{
                    'text-green-600': battleResult === 'victory',
                    'text-red-600': battleResult === 'defeat',
                    'text-blue-600': !['victory', 'defeat'].includes(
                      battleResult
                    ),
                  }"
                  class="text-3xl font-bold mb-4"
                >
                  {{
                    battleResult === "victory"
                      ? pvpMode === "battle"
                        ? t('battle.pvpVictory')
                        : battleMode === "team"
                          ? t('battle.teamVictory')
                          : t('battle.soloVictory')
                      : battleResult === "defeat"
                        ? pvpMode === "battle"
                          ? t('battle.pvpDefeat')
                          : battleMode === "team"
                            ? t('battle.teamDefeat')
                            : t('battle.soloDefeat')
                        : pvpMode === "battle"
                          ? t('battle.pvpDraw')
                          : battleMode === "team"
                            ? t('battle.teamDraw')
                            : t('battle.soloDraw')
                  }}
                </h2>

                <div class="grid grid-cols-2 gap-6 mb-6">
                  <div class="text-center">
                    <div class="flex items-center justify-center gap-2 mb-2">
                      <span class="text-2xl">🦅</span>
                      <h3 class="font-semibold">
                        {{
                          pvpMode === "battle"
                            ? "你"
                            : battleMode === "team"
                              ? "你的团队"
                              : t('battle.yourPerformance')
                        }}
                      </h3>
                    </div>
                    <div class="text-2xl font-bold text-blue-600">
                      <!--                      {{ battleData.playerScore }} 分-->
                      {{
                        t('battle.playerScore', {
                          score: battleData.playerScore
                        })
                      }}
                    </div>
                    <div class="text-sm text-slate-500">
                      <!--                      {{-->
                      <!--                        pvpMode === "battle"-->
                      <!--                          ? currentStats.player1Correct-->
                      <!--                          : battleMode === "team"-->
                      <!--                            ? currentStats.playerTeamCorrect-->
                      <!--                            : currentStats.playerCorrect-->
                      <!--                      }}/{{ currentStats.round }} 正确-->
                      {{
                        t('battle.playerCorrect', {
                          correct: pvpMode === "battle"
                            ? currentStats.player1Correct
                            : battleMode === "team"
                              ? currentStats.playerTeamCorrect
                              : currentStats.playerCorrect,
                          total: currentStats.round
                        })
                      }}
                    </div>
                  </div>
                  <div class="text-center">
                    <div class="flex items-center justify-center gap-2 mb-2">
                      <span class="text-2xl">{{
                          battleData.opponentAvatar
                        }}</span>
                      <h3 class="font-semibold">
                        {{ battleData.opponentName }}
                      </h3>
                    </div>
                    <div class="text-2xl font-bold text-red-600">
                      {{ battleData.opponentScore }} 分
                    </div>
                    <div class="text-sm text-slate-500">
                      <!--                      {{-->
                      <!--                        pvpMode === "battle"-->
                      <!--                          ? currentStats.player2Correct-->
                      <!--                          : battleMode === "team"-->
                      <!--                            ? currentStats.aiTeamCorrect-->
                      <!--                            : currentStats.aiCorrect-->
                      <!--                      }}/{{ currentStats.round }} 正确-->
                      {{
                        t('battle.playerCorrect', {
                          correct: pvpMode === "battle"
                            ? currentStats.player2Correct
                            : battleMode === "team"
                              ? currentStats.aiTeamCorrect
                              : currentStats.aiCorrect,
                          total: currentStats.round
                        })
                      }}
                    </div>
                  </div>
                </div>
                <div
                  v-if="battleResult === 'victory'"
                  class="mb-6 p-4 bg-yellow-50 rounded-lg border border-yellow-200"
                >
                  <h4 class="font-semibold text-yellow-800 mb-2">{{ t('battle.rewards') }}</h4>
                  <div class="flex justify-center gap-4 text-sm">
                    <div class="flex items-center gap-1">
                      <Star class="w-4 h-4 text-yellow-600"/>
                      <span>
                        {{ pvpMode === "battle" ? "80" : "50" }} 排位积分
                      </span>
                    </div>
                    <div class="flex items-center gap-1">
                      <Trophy class="w-4 h-4 text-yellow-600"/>
                      <span>
                        {{
                          pvpMode === "battle"
                            ? "30"
                            : battleMode === "team"
                              ? "25"
                              : "15"
                        }}
                        经验值
                      </span>
                    </div>
                    <div
                      v-if="pvpMode === 'battle'"
                      class="flex items-center gap-1"
                    >
                      <Crown class="w-4 h-4 text-yellow-600"/>
                      <span>真人对战成就</span>
                    </div>
                  </div>
                </div>

                <div class="space-y-4">
                  <button
                    :disabled="!finalTestResult"
                    class="w-full bg-gradient-to-r from-green-600 to-emerald-600 hover:from-green-700 hover:to-emerald-700 text-white py-2 px-4 rounded-md flex items-center justify-center"
                    @click="handleComplete"
                  >
                    <span class="mr-2">🏆</span>
                    查看数据分析
                  </button>
                  <div class="grid grid-cols-2 gap-3">
                    <button
                      class="bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 text-white py-2 px-4 rounded-md flex items-center justify-center"
                      @click="resetBattle"
                    >
                      <span class="mr-2">🔄</span>
                      再次挑战
                    </button>
                    <button
                      class="border border-slate-300 hover:bg-slate-50 py-2 px-4 rounded-md flex items-center justify-center"
                      @click="onBack"
                    >
                      <span class="mr-2">←</span>
                      返回大厅
                    </button>
                  </div>
                </div>
              </CardContent>
            </Card>
          </motion.div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, watch, reactive, onUnmounted, onScopeDispose} from "vue";
import {computed} from "vue";
import {motion} from "motion-v";
import {
  Brain,
  Sword,
  Bot,
  Zap,
  Crown,
  Flame,
  Star,
  Sparkles,
  Gamepad2,
  ArrowLeft,
  Trophy,
  Timer,
  Target,
  Shield,
  Rocket,
  ChevronRight,
  Play,
  Pause,
  RotateCcw,
  Check,
  X,
  Circle,
  Square,
  Triangle,
  MousePointer,
  Users,
  Medal,
  TrendingUp,
  Calendar,
  Gift,
  Swords,
  UserCheck,
  Plus,
  UserPlus,
  MessageCircle,
  Eye,
  Search,
  Settings,
  Lock,
  Globe,
  Wifi,
  WifiOff,
  Clock,
  Send,
  Mic,
  MicOff,
  Volume2,
  VolumeX,
  UserX,
  Heart,
  Share2,
  Copy,
  MoreHorizontal,
} from "lucide-vue-next";
import {getAiOpponents, getQuestionTypes} from "~/constants/aiBattleModeData.js";

const {t, locale} = useI18n();
const currentStats = reactive({
  round: 1,
  player1Score: 0,
  player2Score: 0,
  playerTeamScore: 0,
  aiTeamScore: 0,
  playerScore: 0,
  aiScore: 0,
  player1Correct: 0,
  player2Correct: 0,
  playerTeamCorrect: 0,
  aiTeamCorrect: 0,
  playerCorrect: 0,
  aiCorrect: 0,
  timeRemaining: 15,
});
const totalRounds = ref(5);
const timeRemaining = ref(15);

const aiOpponents = getAiOpponents(locale.value)

// 模拟在线玩家数据
const mockOnlinePlayers = [
  {
    id: "1",
    name: "战神小明",
    avatar: "🦅",
    level: 45,
    rank: 1,
    rankPoints: 2850,
    winRate: 75,
    isOnline: true,
    status: "idle",
    currentStreak: 8,
    title: "至尊王者",
    badge: "👑",
  },
  {
    id: "2",
    name: "AI克星",
    avatar: "⚡",
    level: 42,
    rank: 2,
    rankPoints: 2720,
    winRate: 69,
    isOnline: true,
    status: "searching",
    currentStreak: 5,
    title: "星耀大师",
    badge: "⭐",
  },
  {
    id: "3",
    name: "反应王",
    avatar: "🔥",
    level: 38,
    rank: 3,
    rankPoints: 2580,
    winRate: 65,
    isOnline: true,
    status: "in-game",
    currentStreak: 3,
    title: "钻石精英",
    badge: "💎",
  },
  {
    id: "4",
    name: "速算达人",
    avatar: "🧮",
    level: 35,
    rank: 8,
    rankPoints: 2200,
    winRate: 72,
    isOnline: true,
    status: "idle",
    currentStreak: 12,
    title: "铂金高手",
    badge: "🥈",
  },
  {
    id: "5",
    name: "记忆大师",
    avatar: "🧠",
    level: 33,
    rank: 12,
    rankPoints: 1980,
    winRate: 68,
    isOnline: true,
    status: "spectating",
    currentStreak: 4,
    title: "黄金勇士",
    badge: "🥉",
  },
];

// 模拟房间数据
const mockBattleRooms = [
  {
    id: "room1",
    name: "王者争霸赛",
    mode: "ranked",
    maxPlayers: 2,
    currentPlayers: 1,
    players: [mockOnlinePlayers[0]],
    spectators: [],
    status: "waiting",
    settings: {
      rounds: 5,
      timePerRound: 15,
      difficulty: "hard",
      categories: ["全部"],
      allowSpectators: true,
      maxSpectators: 10,
      chatEnabled: true,
      voiceChatEnabled: false,
    },
    createdBy: "1",
    createdAt: new Date(),
    isPrivate: false,
  },
  {
    id: "room2",
    name: "新手友谊赛",
    mode: "casual",
    maxPlayers: 2,
    currentPlayers: 2,
    players: [mockOnlinePlayers[3], mockOnlinePlayers[4]],
    spectators: [mockOnlinePlayers[1]],
    status: "in-progress",
    settings: {
      rounds: 3,
      timePerRound: 20,
      difficulty: "easy",
      categories: ["反应", "记忆"],
      allowSpectators: true,
      maxSpectators: 5,
      chatEnabled: true,
      voiceChatEnabled: true,
    },
    createdBy: "4",
    createdAt: new Date(Date.now() - 300000),
    isPrivate: false,
  },
  {
    id: "room3",
    name: "私人训练室",
    mode: "private",
    maxPlayers: 2,
    currentPlayers: 1,
    players: [mockOnlinePlayers[2]],
    spectators: [],
    status: "waiting",
    settings: {
      rounds: 7,
      timePerRound: 12,
      difficulty: "mixed",
      categories: ["全部"],
      allowSpectators: false,
      maxSpectators: 0,
      chatEnabled: false,
      voiceChatEnabled: false,
    },
    createdBy: "3",
    createdAt: new Date(Date.now() - 120000),
    isPrivate: true,
    password: "123456",
  },
];

// 模拟好友数据
const mockFriends = [
  {
    id: "f1",
    name: "逻辑大神",
    avatar: "🎯",
    level: 40,
    isOnline: true,
    status: "正在对战中...",
    addedDate: new Date(2024, 6, 15),
    mutualFriends: 3,
  },
  {
    id: "f2",
    name: "反应怪物",
    avatar: "⚡",
    level: 36,
    isOnline: true,
    status: "寻找对手...",
    addedDate: new Date(2024, 7, 2),
    mutualFriends: 1,
  },
  {
    id: "f3",
    name: "记忆达人",
    avatar: "🧭",
    level: 28,
    isOnline: false,
    status: "离线",
    addedDate: new Date(2024, 5, 20),
    lastSeen: new Date(2024, 7, 30),
    mutualFriends: 5,
  },
];

// 模拟排行榜数据
const mockLeaderboard = [
  {
    playerId: "1",
    playerName: "战神小明",
    rank: 1,
    rankPoints: 2850,
    wins: 45,
    losses: 12,
    draws: 3,
    winRate: 75,
    totalBattles: 60,
    currentStreak: 8,
    bestStreak: 15,
    averageScore: 87,
    season: "S1",
    title: "至尊王者",
    badge: "👑",
  },
  {
    playerId: "2",
    playerName: "AI克星",
    rank: 2,
    rankPoints: 2720,
    wins: 38,
    losses: 15,
    draws: 2,
    winRate: 69,
    totalBattles: 55,
    currentStreak: 5,
    bestStreak: 12,
    averageScore: 84,
    season: "S1",
    title: "星耀大师",
    badge: "⭐",
  },
  {
    playerId: "3",
    playerName: "反应王",
    rank: 3,
    rankPoints: 2580,
    wins: 42,
    losses: 18,
    draws: 5,
    winRate: 65,
    totalBattles: 65,
    currentStreak: 3,
    bestStreak: 10,
    averageScore: 81,
    season: "S1",
    title: "钻石精英",
    badge: "💎",
  },
];
const activeTab = ref("solo");
const phase = ref("selection");
const preparationCountdown = ref(5);
const preparationStartTime = ref(null);
const selectedAI = ref(null);
const battleMode = ref("solo");

let battleStats = reactive({
  playerScore: 0,
  aiScore: 0,
  round: 1,
  totalRounds: 5,
  timeRemaining: 15,
  playerCorrect: 0,
  aiCorrect: 0,
});
const questionTypes = ref(getQuestionTypes(locale.value));
let teamBattleStats = reactive({
  playerTeamScore: 0,
  aiTeamScore: 0,
  round: 1,
  totalRounds: 6,
  timeRemaining: 20,
  playerTeamCorrect: 0,
  aiTeamCorrect: 0,
  currentPlayerIndex: 0,
  completedChallenges: [],
});
const waitTimeOptions = ref([
  {
    id: 30,
    name: "30秒",
    desc: "快速匹配",
  },
  {id: 60, name: "60秒", desc: "推荐"},
  {
    id: 120,
    name: "2分钟",
    desc: "精确匹配",
  },
  {
    id: 300,
    name: "不限制",
    desc: "等到匹配",
  },
]);

const currentChallenge = ref(null);
const battleStarted = ref(false);
const battleResult = ref(null);
const finalTestResult = ref(null);
const showPlayerAnswer = ref(false);
const showAIAnswer = ref(false);

// AI状态追踪
const aiStatus = ref("waiting");
const aiThinkingProgress = ref(0);
const aiAnswerTime = ref(null);

const playerTeam = ref(["你", "AI队友1", "AI队友2"]);
const selectedTeamSize = ref(3);

// PvP相关状态
const pvpMode = ref("matchmaking");
const isSearching = ref(false);
const searchTime = ref(0);
const matchFound = ref(false);
const currentRoom = ref(null);
const opponent = ref(null);

const pvpBattleStats = reactive({
  player1Score: 0,
  player2Score: 0,
  player1Correct: 0,
  player2Correct: 0,
  round: 1,
  totalRounds: 5,
  timeRemaining: 15,
  currentQuestion: 1,
});
const regionOptions = ref([
  {
    id: "auto",
    name: "自动选择",
    desc: "推荐",
    icon: "mdi:wifi",
  },
  {
    id: "asia",
    name: "亚洲",
    desc: "低延迟",
    icon: "mdi:earth",
  },
  {
    id: "america",
    name: "美洲",
    desc: "稳定连接",
    icon: "mdi:earth",
  },
  {
    id: "europe",
    name: "欧洲",
    desc: "高速网络",
    icon: "mdi:earth",
  },
]);

const chatMessages = ref([]);
const newMessage = ref("");
const showCreateRoom = ref(false);

const roomSettings = reactive({
  rounds: 5,
  timePerRound: 15,
  difficulty: "medium",
  categories: ["全部"],
  allowSpectators: true,
  maxSpectators: 10,
  chatEnabled: true,
  voiceChatEnabled: false,
});

// 匹配设置状态
const matchSettings = reactive({
  mode: "ranked",
  difficulty: "medium",
  region: "auto",
  maxWaitTime: 60,
});

const timerRef = ref(null);
const reactionStartTime = ref(null);
const challengeStartTime = ref(null);

const changeSelectedTeamSize = (value) => {
  selectedTeamSize.value = value;
};

const handleBackToSelection = () => {
  phase.value = "selection";
  selectedAI.value = null;
  battleMode.value = "solo";
  preparationCountdown.value = 5;
  preparationStartTime.value = null;
};

const getCountdownText = (countdown) => {
  let texts = null
  if (locale.value === 'zh') {
    texts = {
      5: "准备就绪！",
      4: "调整心态...",
      3: "专注准备...",
      2: "集中注意力...",
      1: "即将开始！",
    };
  } else if (locale.value === 'en') {
    texts = {
      5: "Ready to go!",
      4: "Getting in the zone...",
      3: "Focusing up...",
      2: "Concentrating...",
      1: "Starting soon!"
    }
  }

  return texts[countdown] || "";
};
const props = defineProps({
  onComplete: {
    type: Function,
    required: true,
  },
  onBack: {
    types: Function,
    required: true,
  },
});
// 提供给父组件的方法
const emit = defineEmits(["complete", "back"]);

// 扩展的挑战题库 - 支持12种题目类型和多种难度
const generateChallenge = (round, isTeamMode = false) => {
  const challengeTypes = [
    "reaction",
    "memory",
    "math",
    "pattern",
    "color",
    "logic",
    "word",
    "sequence",
    "spatial",
    "attention",
    "comparison",
    "calculation",
  ];

  // 根据AI对手的专长调整题目类型权重
  let weightedTypes = [...challengeTypes];
  if (selectedAI.value) {
    if (selectedAI.value.specialties.includes("逻辑推理")) {
      weightedTypes.push("logic", "sequence");
    }
    if (selectedAI.value.specialties.includes("快速决策")) {
      weightedTypes.push("reaction", "attention");
    }
    if (selectedAI.value.specialties.includes("模式识别")) {
      weightedTypes.push("pattern", "spatial");
    }
  }

  const type = weightedTypes[Math.floor(Math.random() * weightedTypes.length)];
  const baseDifficulty = isTeamMode ? "medium" : "easy";
  const difficulty = Math.random() > 0.3 ? baseDifficulty : "hard";

  switch (type) {
    case "reaction":
      const reactionVariants = [
        "当看到绿色圆圈时点击！",
        "看到蓝色方块立即点击！",
        "红色信号出现时快速点击！",
        "当图标闪烁时点击按钮！",
      ];
      return {
        id: round,
        type: "reaction",
        category: "反应速度",
        difficulty,
        question: isTeamMode
          ? "团队反应测试：看到信号立即点击！"
          : reactionVariants[
            Math.floor(Math.random() * reactionVariants.length)
            ],
        correctAnswer: "click",
        completed: false,
      };

    case "memory":
      const length =
        difficulty === "easy"
          ? isTeamMode
            ? 4
            : 3
          : difficulty === "medium"
            ? isTeamMode
              ? 5
              : 4
            : isTeamMode
              ? 6
              : 5;

      const memoryTypes = [
        () => {
          // 数字记忆 - 选择单个正确数字
          const sequence = Array.from(
            {length},
            () => Math.floor(Math.random() * 9) + 1
          );
          const correctIndex = Math.floor(Math.random() * sequence.length);
          const correctItem = sequence[correctIndex];
          // 创建包含正确答案的选项，并添加其他数字作为干扰项
          const distractors = Array.from({length: 3}, () => {
            let num;
            do {
              num = Math.floor(Math.random() * 9) + 1;
            } while (sequence.includes(num));
            return num;
          });
          const allOptions = [...new Set([correctItem, ...distractors])]
            .map(String)
            .slice(0, 4);
          return {
            question: `记住数字序列：${sequence.join(" - ")}，第${
              correctIndex + 1
            }个数字是？`,
            options: allOptions,
            correctAnswer: correctItem.toString(),
          };
        },
        () => {
          // 颜色记忆 - 选择单个正确颜色
          const colors = ["红", "蓝", "绿", "黄", "紫", "橙"];
          const sequence = Array.from(
            {length: Math.min(length, 4)},
            () => colors[Math.floor(Math.random() * colors.length)]
          );
          const correctIndex = Math.floor(Math.random() * sequence.length);
          const correctItem = sequence[correctIndex];
          // 创建选项，包含序列中出现的颜色和一些干扰项
          const distractors = colors
            .filter((color) => !sequence.includes(color))
            .slice(0, 2);
          const allOptions = [
            ...new Set([correctItem, ...sequence.slice(0, 2), ...distractors]),
          ].slice(0, 4);
          return {
            question: `记住颜色序列：${sequence.join(" → ")}，第${
              correctIndex + 1
            }个颜色是？`,
            options: allOptions,
            correctAnswer: correctItem,
          };
        },
        () => {
          // 字母记忆 - 选择单个正确字母
          const letters = ["A", "B", "C", "D", "E", "F"];
          const sequence = Array.from(
            {length: Math.min(length, 4)},
            () => letters[Math.floor(Math.random() * letters.length)]
          );
          const correctIndex = Math.floor(Math.random() * sequence.length);
          const correctItem = sequence[correctIndex];
          // 创建选项
          const distractors = letters
            .filter((letter) => !sequence.includes(letter))
            .slice(0, 2);
          const allOptions = [
            ...new Set([correctItem, ...sequence.slice(0, 2), ...distractors]),
          ].slice(0, 4);
          return {
            question: `记住字母序列：${sequence.join(" - ")}，第${
              correctIndex + 1
            }个字母是？`,
            options: allOptions,
            correctAnswer: correctItem,
          };
        },
      ];
      const memoryChallenge =
        memoryTypes[Math.floor(Math.random() * memoryTypes.length)]();
      return {
        id: round,
        type: "memory",
        category: "记忆测试",
        difficulty,
        question: memoryChallenge.question,
        options: memoryChallenge.options,
        correctAnswer: memoryChallenge.correctAnswer,
        completed: false,
      };

    case "math":
      const mathTypes = [
        () => {
          const a =
            Math.floor(Math.random() * (difficulty === "hard" ? 100 : 50)) + 5;
          const b =
            Math.floor(Math.random() * (difficulty === "hard" ? 50 : 30)) + 5;
          const op = ["+", "-"][Math.floor(Math.random() * 2)];
          const result = op === "+" ? a + b : a - b;
          // 生成干扰选项
          const wrongOptions = [
            result + Math.floor(Math.random() * 10) + 1,
            result - Math.floor(Math.random() * 10) - 1,
            result + Math.floor(Math.random() * 5) + 5,
          ].filter((n) => n > 0 && n !== result);
          const allOptions = [result, ...wrongOptions.slice(0, 3)].sort(
            () => Math.random() - 0.5
          );
          return {
            question: `${a} ${op} ${b} = ?`,
            answer: result.toString(),
            options: allOptions.map(String),
          };
        },
        () => {
          const a = Math.floor(Math.random() * 12) + 2;
          const b =
            Math.floor(Math.random() * (difficulty === "hard" ? 12 : 8)) + 2;
          const result = a * b;
          // 生成干扰选项
          const wrongOptions = [
            result + a, // 常见错误：加法而不是乘法
            result - b, // 常见错误：减法
            (a + 1) * b, // 常见错误：a+1
            a * (b + 1), // 常见错误：b+1
          ].filter((n) => n > 0 && n !== result);
          const uniqueWrongOptions = [...new Set(wrongOptions)].slice(0, 3);
          const allOptions = [result, ...uniqueWrongOptions].sort(
            () => Math.random() - 0.5
          );
          return {
            question: `${a} × ${b} = ?`,
            answer: result.toString(),
            options: allOptions.map(String),
          };
        },
        () => {
          const nums = Array.from(
            {length: 3},
            () => Math.floor(Math.random() * 20) + 1
          );
          const result = nums.reduce((sum, num) => sum + num, 0);
          // 生成干扰选项
          const wrongOptions = [
            result + Math.floor(Math.random() * 5) + 1,
            result - Math.floor(Math.random() * 5) - 1,
            result + nums[0], // 常见错误：重复加第一个数
            result - nums[2], // 常见错误：减最后一个数
          ].filter((n) => n > 0 && n !== result);
          const uniqueWrongOptions = [...new Set(wrongOptions)].slice(0, 3);
          const allOptions = [result, ...uniqueWrongOptions].sort(
            () => Math.random() - 0.5
          );
          return {
            question: `${nums.join(" + ")} = ?`,
            answer: result.toString(),
            options: allOptions.map(String),
          };
        },
        () => {
          const base = Math.floor(Math.random() * 8) + 2;
          const exp =
            difficulty === "hard" ? Math.floor(Math.random() * 3) + 3 : 2;
          const result = Math.pow(base, exp);
          // 生成干扰选项
          const wrongOptions = [
            base * exp, // 常见错误：乘法而不是乘方
            Math.pow(base, exp - 1), // 指数减1
            Math.pow(base - 1, exp), // 底数减1
            result + base, // 加上底数
          ].filter((n) => n > 0 && n !== result);
          const uniqueWrongOptions = [...new Set(wrongOptions)].slice(0, 3);
          const allOptions = [result, ...uniqueWrongOptions].sort(
            () => Math.random() - 0.5
          );
          return {
            question: `${base}^${exp} = ?`,
            answer: result.toString(),
            options: allOptions.map(String),
          };
        },
      ];
      const mathChallenge =
        mathTypes[Math.floor(Math.random() * mathTypes.length)]();
      return {
        id: round,
        type: "math",
        category: "数学计算",
        difficulty,
        question: mathChallenge.question,
        options: mathChallenge.options,
        correctAnswer: mathChallenge.answer,
        completed: false,
      };

    case "pattern":
      const patternTypes = [
        () => {
          const symbols = ["🔴", "🔵", "🟢", "🟡", "⭐", "🌙"];
          const patternLength = difficulty === "hard" ? 5 : 4;
          // 创建简单的交替模式
          const pattern = Array.from(
            {length: patternLength},
            (_, i) => symbols[i % 2]
          );
          const nextSymbol = symbols[patternLength % 2]; // 下一个应该是什么
          // 创建包含正确答案的选项
          const wrongOptions = symbols
            .filter((s) => s !== nextSymbol)
            .slice(0, 3);
          const allOptions = [nextSymbol, ...wrongOptions].sort(
            () => Math.random() - 0.5
          );
          return {
            question: `找规律：${pattern.join(" ")} ?`,
            options: allOptions,
            answer: nextSymbol,
          };
        },
        () => {
          const sequences = [
            {nums: [2, 4, 6, 8], next: 10, rule: "+2"},
            {nums: [1, 3, 5, 7], next: 9, rule: "+2"},
            {nums: [2, 4, 8, 16], next: 32, rule: "×2"},
            {nums: [1, 2, 4, 8], next: 16, rule: "×2"},
            {nums: [10, 8, 6, 4], next: 2, rule: "-2"},
            {nums: [20, 16, 12, 8], next: 4, rule: "-4"},
          ];
          const selected =
            sequences[Math.floor(Math.random() * sequences.length)];
          const wrongOptions = [
            selected.next + 1,
            selected.next - 1,
            selected.next + 2,
          ].filter((n) => n !== selected.next && n > 0);
          const allOptions = [selected.next, ...wrongOptions.slice(0, 3)].sort(
            () => Math.random() - 0.5
          );
          return {
            question: `数列规律：${selected.nums.join(", ")} ?`,
            options: allOptions.map(String),
            answer: selected.next.toString(),
          };
        },
      ];
      const patternChallenge =
        patternTypes[Math.floor(Math.random() * patternTypes.length)]();
      return {
        id: round,
        type: "pattern",
        category: "模式识别",
        difficulty,
        question: patternChallenge.question,
        options: patternChallenge.options,
        correctAnswer: patternChallenge.answer,
        completed: false,
      };

    case "color":
      const colorChallenges = [
        () => {
          const colors = ["红色", "蓝色", "绿色", "黄色", "紫色", "橙色"];
          const colorEmojis = ["🔴", "🔵", "🟢", "🟡", "🟣", "🟠"];
          const index = Math.floor(Math.random() * colors.length);
          const numOptions = difficulty === "hard" ? 6 : 4;
          const selectedOptions = colorEmojis.slice(0, numOptions);
          // 确保正确答案在选项中
          if (!selectedOptions.includes(colorEmojis[index])) {
            selectedOptions[0] = colorEmojis[index];
          }
          return {
            question: `选择 ${colors[index]}`,
            options: selectedOptions,
            answer: colorEmojis[index],
          };
        },
        () => {
          const colorMix = [
            {
              name: "橙色",
              mix: "红+黄",
              emoji: "🟠",
              options: ["🔴", "🟡", "🟠", "🟢"],
            },
            {
              name: "紫色",
              mix: "红+蓝",
              emoji: "🟣",
              options: ["🔴", "🔵", "🟣", "🟢"],
            },
            {
              name: "绿色",
              mix: "蓝+黄",
              emoji: "🟢",
              options: ["🔵", "🟡", "🟢", "🔴"],
            },
          ];
          const mix = colorMix[Math.floor(Math.random() * colorMix.length)];
          return {
            question: `${mix.mix} = ?`,
            options: mix.options,
            answer: mix.emoji,
          };
        },
      ];
      const colorChallenge =
        colorChallenges[Math.floor(Math.random() * colorChallenges.length)]();
      return {
        id: round,
        type: "color",
        category: "颜色识别",
        difficulty,
        question: colorChallenge.question,
        options: colorChallenge.options,
        correctAnswer: colorChallenge.answer,
        completed: false,
      };

    case "logic":
      const logicChallenges = [
        () => {
          const statements = [
            {
              premise: "所有猫都是动物，小花是猫",
              conclusion: "小花是动物",
              answer: "正确",
            },
            {
              premise: "有些鸟会飞，企鹅是鸟",
              conclusion: "企鹅会飞",
              answer: "错误",
            },
            {
              premise: "如果下雨，地面会湿",
              conclusion: "地面湿了，所以下雨了",
              answer: "错误",
            },
            {
              premise: "只有努力才能成功，小明成功了",
              conclusion: "小明努力了",
              answer: "正确",
            },
          ];
          const stmt =
            statements[Math.floor(Math.random() * statements.length)];
          return {
            question: `${stmt.premise}。结论：${stmt.conclusion}`,
            options: ["正确", "错误"],
            answer: stmt.answer,
          };
        },
        () => {
          const puzzles = [
            {
              puzzle: "A比B大，B比C大",
              question: "谁最大？",
              options: ["A", "B", "C"],
              answer: "A",
            },
            {
              puzzle: "红球比蓝球重，蓝球比绿球重",
              question: "谁最轻？",
              options: ["红球", "蓝球", "绿球"],
              answer: "绿球",
            },
            {
              puzzle: "如果今天是周一，明天是？",
              question: "",
              options: ["周二", "周三", "周日"],
              answer: "周二",
            },
          ];
          const puzzle = puzzles[Math.floor(Math.random() * puzzles.length)];
          return {
            question: `${puzzle.puzzle}${
              puzzle.question ? ` ${puzzle.question}` : ""
            }`,
            options: puzzle.options,
            answer: puzzle.answer,
          };
        },
      ];
      const logicChallenge =
        logicChallenges[Math.floor(Math.random() * logicChallenges.length)]();
      return {
        id: round,
        type: "logic",
        category: "逻辑推理",
        difficulty,
        question: logicChallenge.question,
        options: logicChallenge.options,
        correctAnswer: logicChallenge.answer,
        completed: false,
      };

    case "word":
      const wordChallenges = [
        () => {
          const words = [
            {
              word: "快乐",
              opposite: "痛苦",
              options: ["痛苦", "高兴", "平静", "激动"],
            },
            {
              word: "温暖",
              opposite: "寒冷",
              options: ["寒冷", "凉爽", "热烈", "舒适"],
            },
            {
              word: "光明",
              opposite: "黑暗",
              options: ["黑暗", "明亮", "闪耀", "朦胧"],
            },
            {
              word: "勇敢",
              opposite: "胆怯",
              options: ["胆怯", "无畏", "坚强", "谨慎"],
            },
          ];
          const wordPair = words[Math.floor(Math.random() * words.length)];
          return {
            question: `"${wordPair.word}"的反义词是？`,
            options: wordPair.options,
            answer: wordPair.opposite,
          };
        },
        () => {
          const analogies = [
            {
              analogy: "鸟:天空 = 鱼:?",
              options: ["水", "陆地", "空气", "树"],
              answer: "水",
            },
            {
              analogy: "医生:医院 = 老师:?",
              options: ["学校", "医院", "工厂", "商店"],
              answer: "学校",
            },
            {
              analogy: "手:写字 = 脚:?",
              options: ["走路", "跑步", "思考", "看书"],
              answer: "走路",
            },
          ];
          const analogy =
            analogies[Math.floor(Math.random() * analogies.length)];
          return {
            question: analogy.analogy,
            options: analogy.options,
            answer: analogy.answer,
          };
        },
      ];
      const wordChallenge =
        wordChallenges[Math.floor(Math.random() * wordChallenges.length)]();
      return {
        id: round,
        type: "word",
        category: "语言理解",
        difficulty,
        question: wordChallenge.question,
        options: wordChallenge.options,
        correctAnswer: wordChallenge.answer,
        completed: false,
      };

    case "sequence":
      const sequenceChallenges = [
        () => {
          const sequences = [
            {seq: [1, 1, 2, 3, 5], next: 8, type: "斐波那契"},
            {seq: [2, 6, 18, 54], next: 162, type: "乘3"},
            {seq: [100, 81, 64, 49], next: 36, type: "平方递减"},
            {seq: [1, 4, 9, 16], next: 25, type: "平方数"},
            {seq: [2, 4, 8, 16], next: 32, type: "乘2"},
            {seq: [3, 6, 12, 24], next: 48, type: "乘2"},
            {seq: [10, 20, 30, 40], next: 50, type: "加10"},
            {seq: [5, 10, 15, 20], next: 25, type: "加5"},
          ];
          const seqData =
            sequences[Math.floor(Math.random() * sequences.length)];
          // 生成合理的错误选项
          const wrongOptions = [];
          if (seqData.next > 10) {
            wrongOptions.push(seqData.next + Math.floor(seqData.next * 0.1));
            wrongOptions.push(seqData.next - Math.floor(seqData.next * 0.1));
            wrongOptions.push(Math.floor(seqData.next * 1.5));
          } else {
            wrongOptions.push(seqData.next + 1);
            wrongOptions.push(seqData.next + 2);
            wrongOptions.push(seqData.next - 1);
          }
          const uniqueWrongOptions = [
            ...new Set(wrongOptions.filter((n) => n > 0 && n !== seqData.next)),
          ];
          const allOptions = [
            seqData.next,
            ...uniqueWrongOptions.slice(0, 3),
          ].sort(() => Math.random() - 0.5);
          return {
            question: `数列：${seqData.seq.join(", ")} → ?`,
            options: allOptions.map(String),
            answer: seqData.next.toString(),
          };
        },
      ];
      const sequenceChallenge =
        sequenceChallenges[
          Math.floor(Math.random() * sequenceChallenges.length)
          ]();
      return {
        id: round,
        type: "sequence",
        category: "序列推理",
        difficulty,
        question: sequenceChallenge.question,
        options: sequenceChallenge.options,
        correctAnswer: sequenceChallenge.answer,
        completed: false,
      };

    case "calculation":
      const calculationChallenges = [
        () => {
          // 简单价格计算
          const item1Price = (Math.random() * 50 + 10).toFixed(2);
          const item2Price = (Math.random() * 30 + 5).toFixed(2);
          const total = (
            parseFloat(item1Price) + parseFloat(item2Price)
          ).toFixed(2);
          // 生成干扰项
          const wrongOptions = [
            (parseFloat(total) + Math.random() * 2).toFixed(2),
            (parseFloat(total) - Math.random() * 2).toFixed(2),
            (parseFloat(total) + Math.random() * 5).toFixed(2),
          ];
          const allOptions = [total, ...wrongOptions].sort(
            () => Math.random() - 0.5
          );
          return {
            question: `商品A: ￥${item1Price}，商品B: ￥${item2Price}，总价格是？`,
            options: allOptions,
            answer: total, // 注意这里不包含货币符号
          };
        },
        () => {
          // 折扣计算
          const originalPrice = Math.floor(Math.random() * 200) + 50;
          const discount = [0.1, 0.2, 0.3, 0.15, 0.25][
            Math.floor(Math.random() * 5)
            ];
          const finalPrice = (originalPrice * (1 - discount)).toFixed(2);
          // 生成干扰项
          const wrongOptions = [
            (originalPrice * discount).toFixed(2), // 错误：只算折扣金额
            (originalPrice * (1 + discount)).toFixed(2), // 错误：加折扣
            (parseFloat(finalPrice) + Math.random() * 10).toFixed(2),
          ];
          const allOptions = [finalPrice, ...wrongOptions].sort(
            () => Math.random() - 0.5
          );
          return {
            question: `原价￥${originalPrice}，打${Math.floor(
              (1 - discount) * 10
            )}折后价格是？`,
            options: allOptions,
            answer: finalPrice,
          };
        },
        () => {
          // 税率计算
          const basePrice = Math.floor(Math.random() * 100) + 20;
          const taxRate = 0.13; // 13%税率
          const finalPrice = (basePrice * (1 + taxRate)).toFixed(2);
          // 生成干扰项
          const wrongOptions = [
            (basePrice * taxRate).toFixed(2), // 错误：只算税额
            (basePrice * (1 + 0.1)).toFixed(2), // 错误：10%税率
            (parseFloat(finalPrice) - Math.random() * 5).toFixed(2),
          ];
          const allOptions = [finalPrice, ...wrongOptions].sort(
            () => Math.random() - 0.5
          );
          return {
            question: `商品价格￥${basePrice}，加13%税后总价是？`,
            options: allOptions,
            answer: finalPrice,
          };
        },
      ];
      const calculationChallenge =
        calculationChallenges[
          Math.floor(Math.random() * calculationChallenges.length)
          ]();
      return {
        id: round,
        type: "calculation",
        category: "计算题",
        difficulty,
        question: calculationChallenge.question,
        options: calculationChallenge.options,
        correctAnswer: calculationChallenge.answer,
        completed: false,
      };

    case "spatial":
      const spatialChallenges = [
        () => {
          const shapes = ["⬆️", "⬇️", "⬅️", "➡️"];
          const rotations = [
            {shape: "⬆️", rotated: "➡️", desc: "顺时针90°"},
            {shape: "➡️", rotated: "⬇️", desc: "顺时针90°"},
            {shape: "⬇️", rotated: "⬅️", desc: "顺时针90°"},
            {shape: "⬅️", rotated: "⬆️", desc: "顺时针90°"},
          ];
          const rotation =
            rotations[Math.floor(Math.random() * rotations.length)];
          return {
            question: `${rotation.shape} 顺时针旋转90° = ?`,
            options: shapes,
            answer: rotation.rotated,
          };
        },
        () => {
          const mirrorPairs = [
            {original: "◀️", mirrored: "▶️"},
            {original: "↖️", mirrored: "↗️"},
            {original: "↙️", mirrored: "↘️"},
          ];
          const pair =
            mirrorPairs[Math.floor(Math.random() * mirrorPairs.length)];
          // 确保选项包含所有可能的镜像答案
          const allMirrorOptions = ["◀️", "▶️", "↖️", "↗️", "↙️", "↘️"];
          return {
            question: `${pair.original} 的镜像是？`,
            options: allMirrorOptions,
            answer: pair.mirrored,
          };
        },
      ];
      const spatialChallenge =
        spatialChallenges[
          Math.floor(Math.random() * spatialChallenges.length)
          ]();
      return {
        id: round,
        type: "spatial",
        category: t('script.spatialReasoning'),
        difficulty,
        question: spatialChallenge.question,
        options: spatialChallenge.options,
        correctAnswer: spatialChallenge.answer,
        completed: false,
      };

    case "attention":
      const attentionChallenges = [
        () => {
          const chars = ["A", "B", "C", "D"];
          const target = chars[Math.floor(Math.random() * chars.length)];
          const sequence = Array.from(
            {length: difficulty === "hard" ? 8 : 6},
            () =>
              Math.random() < 0.3
                ? target
                : chars[Math.floor(Math.random() * chars.length)]
          );
          const count = sequence.filter((c) => c === target).length;
          return {
            question: `数出字母 ${target} 的个数：${sequence.join(" ")}`,
            options: [count, count + 1, count - 1, count + 2]
              .filter((n) => typeof n === "number" && n >= 0) // 确保是数字且大于等于0
              .slice(0, 4)
              .map((item) => String(item || "")), // 确保转换为字符串，并处理可能的 null/undefined
            answer: count.toString(),
          };
        },
      ];
      const attentionChallenge =
        attentionChallenges[
          Math.floor(Math.random() * attentionChallenges.length)
          ]();
      return {
        id: round,
        type: "attention",
        category: "注意力测试",
        difficulty,
        question: attentionChallenge.question,
        options: attentionChallenge.options,
        correctAnswer: attentionChallenge.answer,
        completed: false,
      };

    case "comparison":
      const comparisonChallenges = [
        () => {
          const nums = Array.from(
            {length: 4},
            () => Math.floor(Math.random() * 100) + 1
          );
          const max = Math.max(...nums);
          return {
            question: `找出最大数：${nums.join(", ")}`,
            options: nums.map(String),
            answer: max.toString(),
          };
        },
        () => {
          const items = [
            {name: "苹果", weight: 150, unit: "g"},
            {name: "香蕉", weight: 120, unit: "g"},
            {name: "橙子", weight: 200, unit: "g"},
            {name: "葡萄", weight: 80, unit: "g"},
          ];
          const selected = items.slice(0, 3);
          const heaviest = selected.reduce((a, b) =>
            a.weight > b.weight ? a : b
          );
          return {
            question: `哪个最重？`,
            options: selected.map(
              (item) => `${item.name}(${item.weight}${item.unit})`
            ),
            answer: `${heaviest.name}(${heaviest.weight}${heaviest.unit})`,
          };
        },
      ];
      const comparisonChallenge =
        comparisonChallenges[
          Math.floor(Math.random() * comparisonChallenges.length)
          ]();
      return {
        id: round,
        type: "comparison",
        category: "比较分析",
        difficulty,
        question: comparisonChallenge.question,
        options: comparisonChallenge.options,
        correctAnswer: comparisonChallenge.answer,
        completed: false,
      };

    default:
      return generateChallenge(round, isTeamMode);
  }
};

// AI答题逻辑 - 根据AI专长和题目类型调整表现
const generateAIAnswer = (challenge) => {
  let baseTime = 1000 + Math.random() * 2000;
  let difficultyMultiplier = 1 - (selectedAI.value?.difficulty || 0.5) * 0.5;
  let errorRate = 1 - (selectedAI.value?.difficulty || 0.5);

  // 根据AI专长调整表现
  if (selectedAI.value?.specialties) {
    const specialtyBonus = getSpecialtyBonus(
      challenge.category,
      selectedAI.value.specialties
    );
    difficultyMultiplier *= 1 - specialtyBonus * 0.3; // 专长题目用时减少
    errorRate *= 1 - specialtyBonus * 0.4; // 专长题目错误率降低
  }

  // 根据题目难度调整
  const difficultyFactor =
    {
      easy: 0.8,
      medium: 1.0,
      hard: 1.3,
    }[challenge.difficulty] || 1.0;

  baseTime *= difficultyFactor;
  errorRate *= difficultyFactor;

  // 反应测试特殊处理
  if (challenge.type === "reaction") {
    baseTime = 300 + Math.random() * 800; // 反应测试用时更短
    errorRate *= 0.5; // 反应测试错误率更低
  }

  const actualTime = baseTime * difficultyMultiplier;
  const willMakeError = Math.random() < Math.min(0.4, errorRate); // 错误率上限40%

  // 如果有选项，优先从选项中选择答案
  if (challenge.options && challenge.options.length > 0) {
    if (willMakeError) {
      // 选择错误答案：从选项中排除正确答案
      const wrongOptions = challenge.options.filter(
        (opt) => String(opt) !== String(challenge.correctAnswer)
      );
      if (wrongOptions.length > 0) {
        return {
          answer: wrongOptions[Math.floor(Math.random() * wrongOptions.length)],
          time: actualTime,
        };
      }
    }

    // 确保正确答案在选项中，如果不在则从选项中随机选择一个
    if (challenge.options.includes(String(challenge.correctAnswer))) {
      return {
        answer: challenge.correctAnswer,
        time: actualTime,
      };
    } else {
      // 如果正确答案不在选项中，从选项中随机选择
      console.warn(
        "正确答案不在选项中，随机选择:",
        challenge.correctAnswer,
        challenge.options
      );
      return {
        answer:
          challenge.options[
            Math.floor(Math.random() * challenge.options.length)
            ],
        time: actualTime,
      };
    }
  }

  // 对于数值类型的错误答案（没有选项的情况）
  if (willMakeError && typeof challenge.correctAnswer === "number") {
    const deviation = Math.floor(Math.random() * 10) + 1;
    const wrongAnswer =
      Math.random() > 0.5
        ? challenge.correctAnswer + deviation
        : Math.max(0, challenge.correctAnswer - deviation);
    return {
      answer: wrongAnswer,
      time: actualTime,
    };
  }

  // 默认返回正确答案
  return {
    answer: challenge.correctAnswer,
    time: actualTime,
  };
};

// 获取AI在特定类别的专长加成
const getSpecialtyBonus = (category, specialties) => {
  const categoryMapping = {
    反应速度: ["基础反应", "快速决策", "反应速度", "动作协调"],
    记忆测试: ["基础反应", "简单逻辑"],
    数学计算: ["简单逻辑", "策略规划"],
    计算应用: ["简单逻辑", "策略规划"],
    模式识别: ["逻辑推理", "策略规划", "模式识别"],
    颜色识别: ["基础反应", "模式识别"],
    逻辑推理: ["逻辑推理", "策略规划", "适应性学习"],
    语言理解: ["逻辑推理", "适应性学习"],
    序列推理: ["逻辑推理", "模式识别", "策略规划"],
    空间推理: ["模式识别", "策略规划"],
    注意力测试: ["快速决策", "反应速度", "完美执行"],
    比较分析: ["策略规划", "适应性学习"],
  };

  const relevantSpecialties = categoryMapping[category] || [];
  const matchCount = specialties.filter((specialty) =>
    relevantSpecialties.some(
      (relevant) => specialty.includes(relevant) || relevant.includes(specialty)
    )
  ).length;

  return Math.min(1.0, matchCount * 0.5); // 最大50%加成
};
// 开始单人对战
const startSoloBattle = (ai) => {
  selectedAI.value = ai;
  phase.value = "preparation";
  preparationCountdown.value = 5;
  Object.assign(battleStats, {
    // Use Object.assign to mutate existing reactive object
    playerScore: 0,
    aiScore: 0,
    totalRounds: 5,
    timeRemaining: 15,
    playerCorrect: 0,
    aiCorrect: 0,
  });

  // 开始倒计时
  startPreparationCountdown();
};

// 开始团队对战
const startTeamBattle = (ai) => {
  selectedAI.value = ai;
  battleMode.value = "team";
  phase.value = "preparation";
  preparationCountdown.value = 5;
  Object.assign(teamBattleStats, {
    // Use Object.assign to mutate existing reactive object
    playerTeamScore: 0,
    aiTeamScore: 0,
    totalRounds: 6,
    timeRemaining: 20,
    playerTeamCorrect: 0,
    aiTeamCorrect: 0,
    currentPlayerIndex: 0,
    completedChallenges: [],
  });

  // 开始倒计时
  startPreparationCountdown();
};
// 开始准备倒计时 - 使用精确时间计算
let countdownTimer = null;
const startPreparationCountdown = () => {
  const startTime = Date.now();
  preparationStartTime.value = startTime;

  countdownTimer = setInterval(() => {
    const elapsed = Date.now() - startTime;
    const remaining = Math.max(0, 5 - Math.floor(elapsed / 1000));

    preparationCountdown.value = remaining;

    if (remaining <= 0) {
      clearInterval(countdownTimer);
      // 倒计时结束，开始对战
      phase.value = "battle";
      battleStarted.value = true;
      preparationStartTime.value = null;
      if (battleMode.value === "team") {
        startNewTeamRound();
      } else {
        startNewRound();
      }
    }
  }, 100); // 使用100ms间隔进行更精确的检查

  // 立即执行一次以避免初始延迟
  const elapsed = Date.now() - startTime;
  const remaining = Math.max(0, 5 - Math.floor(elapsed / 1000));
  preparationCountdown.value = remaining;
};
// 组件卸载时清除定时器
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
});
// 开始新回合
const startNewRound = () => {
  const challenge = generateChallenge(battleStats.round, false);
  currentChallenge.value = challenge;
  console.log("生成的 currentChallenge:", currentChallenge.value);
  showPlayerAnswer.value = false;
  showAIAnswer.value = false;
  aiStatus.value = "thinking";
  aiThinkingProgress.value = 0;
  aiAnswerTime.value = null;
  currentStats.timeRemaining = 15;

  // 记录挑战开始时间（用于准确计算用户答题时间）
  const challengeStart = Date.now();
  challengeStartTime.value = challengeStart;
  if (challenge.type === "reaction") {
    const delay = 2000 + Math.random() * 3000;
    setTimeout(() => {
      reactionStartTime.value = Date.now();
    }, delay);
  }

  // 生成AI答案时确保答案有效
  const aiResult = generateAIAnswer(challenge);

  // 验证AI答案是否有效
  if (
    challenge.options &&
    !challenge.options.includes(String(aiResult.answer))
  ) {
    console.warn(
      "AI答案无效，重新生成:",
      aiResult.answer,
      "可选项:",
      challenge.options
    );
    // 如果AI答案无效，从选项中随机选择一个
    const randomOption =
      challenge.options[Math.floor(Math.random() * challenge.options.length)];
    aiResult.answer = randomOption;
  }

  const startTime = Date.now();

  // 模拟AI思考进度
  const thinkingInterval = setInterval(() => {
    const elapsed = Date.now() - startTime;
    const progress = Math.min((elapsed / aiResult.time) * 100, 100);
    aiThinkingProgress.value = progress;
    if (progress >= 100) {
      clearInterval(thinkingInterval);
      aiStatus.value = "answering";
    }
  }, 50);

  setTimeout(() => {
    currentChallenge.value = {
      ...currentChallenge.value,
      aiAnswer: aiResult.answer,
    };
    showAIAnswer.value = true;
    aiStatus.value = "completed";
    aiAnswerTime.value = aiResult.time / 1000;
    clearInterval(thinkingInterval);
  }, aiResult.time);
};

// 开始新团队回合
const startNewTeamRound = () => {
  const challenge = generateChallenge(teamBattleStats.round, true);
  currentChallenge.value = challenge;
  console.log("生成的 currentChallenge (团队模式):", currentChallenge.value); // 添加这一行
  showPlayerAnswer.value = false;
  showAIAnswer.value = false;
  aiStatus.value = "thinking";
  aiThinkingProgress.value = 0;
  aiAnswerTime.value = null;
  currentStats.timeRemaining = 20;

  // 记录挑战开始时间（用于准确计算用户答题时间）
  const challengeStart = Date.now();
  challengeStartTime.value = challengeStart;

  if (challenge.type === "reaction") {
    const delay = 2000 + Math.random() * 4000;
    setTimeout(() => {
      reactionStartTime.value = Date.now();
    }, delay);
  }

  // 生成AI答案时确保答案有效
  const aiResult = generateAIAnswer(challenge);

  // 验证AI答案是否有效
  if (
    challenge.options &&
    !challenge.options.includes(String(aiResult.answer))
  ) {
    console.warn(
      "AI答案无效，重新生成:",
      aiResult.answer,
      "可选项:",
      challenge.options
    );
    // 如果AI答案无效，从选项中随机选择一个
    const randomOption =
      challenge.options[Math.floor(Math.random() * challenge.options.length)];
    aiResult.answer = randomOption;
  }

  const startTime = Date.now();

  // 模拟AI思考进度
  const thinkingInterval = setInterval(() => {
    const elapsed = Date.now() - startTime;
    const progress = Math.min((elapsed / aiResult.time) * 100, 100);
    aiThinkingProgress.value = progress;

    if (progress >= 100) {
      clearInterval(thinkingInterval);
      aiStatus.value = "answering";
    }
  }, 50);

  setTimeout(() => {
    currentChallenge.value = {
      ...currentChallenge.value,
      aiAnswer: aiResult.answer,
    };
    showAIAnswer.value = true;
    aiStatus.value = "completed";
    aiAnswerTime.value = aiResult.time / 1000;
    clearInterval(thinkingInterval);
  }, aiResult.time);
};

// 处理玩家答题
const handleAnswer = (answer) => {
  if (!currentChallenge.value || currentChallenge.value.completed) {
    return;
  }

  let timeToAnswer = 0;
  if (currentChallenge.value.type === "reaction" && reactionStartTime.value) {
    timeToAnswer = (Date.now() - reactionStartTime.value) / 1000;
  } else if (challengeStartTime.value) {
    timeToAnswer = (Date.now() - challengeStartTime.value) / 1000;
  }

  currentChallenge.value.playerAnswer = answer;
  currentChallenge.value.timeToAnswer = timeToAnswer;
  currentChallenge.value.completed = true;

  showPlayerAnswer.value = true;

  const isCorrect =
    String(answer) === String(currentChallenge.value.correctAnswer);
  const basePoints = battleMode.value === "team" ? 25 : 20;
  const points = isCorrect
    ? currentChallenge.value.type === "reaction"
      ? Math.max(10, basePoints + 15 - timeToAnswer * 2)
      : basePoints
    : 0;

  if (battleMode.value === "team") {
    teamBattleStats.playerTeamScore += points;
    teamBattleStats.playerTeamCorrect += isCorrect ? 1 : 0;
  } else {
    battleStats.playerScore += points;
    battleStats.playerCorrect += isCorrect ? 1 : 0;
    currentStats.playerScore += points;
    currentStats.playerCorrect += isCorrect ? 1 : 0;
  }

  console.log("battleStats", battleStats);

  setTimeout(() => {
    const aiIsCorrect =
      String(currentChallenge.value.aiAnswer) ===
      String(currentChallenge.value.correctAnswer);
    const aiPoints = aiIsCorrect ? basePoints : 0;

    if (battleMode.value === "team") {
      teamBattleStats.aiTeamScore += aiPoints;
      teamBattleStats.aiTeamCorrect += aiIsCorrect ? 1 : 0;

      setTimeout(() => {
        if (teamBattleStats.round >= teamBattleStats.totalRounds) {
          finishBattle();
        } else {
          teamBattleStats.round++;
          currentStats.round = teamBattleStats.round;
          startNewTeamRound();
        }
      }, 2000);
    } else {
      // solo mode
      battleStats.aiScore += aiPoints;
      battleStats.aiCorrect += aiIsCorrect ? 1 : 0;
      currentStats.aiScore += aiPoints;
      currentStats.aiCorrect += aiIsCorrect ? 1 : 0;
      setTimeout(() => {
        if (battleStats.round >= battleStats.totalRounds) {
          finishBattle();
        } else {
          battleStats.round++;
          currentStats.round = battleStats.round;
          startNewRound();
        }
      }, 2000);
    }
  }, 1000);
};

// 搜索匹配计时器
watch(
  isSearching,
  (newValue) => {
    if (newValue) {
      const searchTimer = setInterval(() => {
        searchTime.value += 1;

        if (searchTime.value >= 30) {
          matchFound.value = true;
          isSearching.value = false;
          searchTime.value = 0;
        }
      }, 1000);

      // 返回清理函数
      return () => clearInterval(searchTimer);
    }
  },
  {immediate: true}
);

// 对战计时器
watch(
  [
    () => battleStarted.value,
    () => phase.value,
    () => currentChallenge.value?.completed,
    () => battleMode.value,
    () => pvpMode.value,
    () => currentStats.timeRemaining, // Watch currentStats.timeRemaining directly
  ],
  ([
     battleStartedVal,
     phaseVal,
     currentChallengeCompleted,
     battleModeVal,
     pvpModeVal,
     battleStatsTime,
     teamBattleStatsTime,
     pvpBattleStatsTime,
   ]) => {
    if (timerRef.value) {
      clearTimeout(timerRef.value);
      timerRef.value = null;
    }

    if (
      battleStartedVal &&
      phaseVal === "battle" &&
      !currentChallengeCompleted
    ) {
      let timeRemaining;
      if (pvpModeVal === "battle") {
        timeRemaining = pvpBattleStatsTime;
      } else if (battleModeVal === "team") {
        timeRemaining = teamBattleStatsTime;
      } else {
        timeRemaining = battleStatsTime;
      }

      if (timeRemaining > 0) {
        timerRef.value = setTimeout(() => {
          currentStats.timeRemaining -= 1;
        }, 1000);
      } else {
        handleTimeout();
      }
    }
  },
  {deep: true}
);

// 单独处理超时逻辑的函数
const handleTimeout = () => {
  if (!currentChallenge.value || currentChallenge.value.completed) {
    return;
  }

  let timeToAnswer = 0;
  if (challengeStartTime.value) {
    timeToAnswer = (Date.now() - challengeStartTime.value) / 1000;
  } else {
    timeToAnswer = battleMode.value === "team" ? 20 : 15;
  }

  currentChallenge.value.playerAnswer = "timeout";
  currentChallenge.value.timeToAnswer = timeToAnswer;
  currentChallenge.value.completed = true;

  showPlayerAnswer.value = true;

  // Player gets 0 points for timeout
  const points = 0;
  const isCorrect = false;

  if (battleMode.value === "team") {
    teamBattleStats.playerTeamScore += points;
    teamBattleStats.playerTeamCorrect += isCorrect ? 1 : 0;
  } else {
    battleStats.playerScore += points;
    battleStats.playerCorrect += isCorrect ? 1 : 0;
  }

  setTimeout(() => {
    const basePoints = battleMode.value === "team" ? 25 : 20;
    const aiIsCorrect =
      String(currentChallenge.value.aiAnswer) ===
      String(currentChallenge.value.correctAnswer);
    const aiPoints = aiIsCorrect ? basePoints : 0;

    if (battleMode.value === "team") {
      teamBattleStats.aiTeamScore += aiPoints;
      teamBattleStats.aiTeamCorrect += aiIsCorrect ? 1 : 0;

      setTimeout(() => {
        if (teamBattleStats.round >= teamBattleStats.totalRounds) {
          finishBattle();
        } else {
          teamBattleStats.round++;
          currentStats.round = teamBattleStats.round;
          startNewTeamRound();
        }
      }, 2000);
    } else {
      // solo mode
      battleStats.aiScore += aiPoints;
      battleStats.aiCorrect += aiIsCorrect ? 1 : 0;

      setTimeout(() => {
        if (battleStats.round >= battleStats.totalRounds) {
          finishBattle();
        } else {
          battleStats.round++;
          currentStats.round = battleStats.round;
          startNewRound();
        }
      }, 2000);
    }
  }, 1000);
};

// 组件卸载时清理
onScopeDispose(() => {
  if (timerRef.value) {
    clearTimeout(timerRef.value);
  }
});

const resetBattle = () => {
  console.log("已经");
  phase.value = "selection";
  selectedAI.value = null;
  battleStarted.value = false;
  battleResult.value = null;
  finalTestResult.value = null;
  currentChallenge.value = null;
  reactionStartTime.value = null;
  challengeStartTime.value = null;
  battleMode.value = "solo";
  preparationCountdown.value = 5;
  preparationStartTime.value = null;

  // 重置AI状态
  aiStatus.value = "waiting";
  aiThinkingProgress.value = 0;
  aiAnswerTime.value = null;

  // 重置PvP状态
  pvpMode.value = "matchmaking";
  isSearching.value = false;
  searchTime.value = 0;
  matchFound.value = false;
  currentRoom.value = null;
  opponent.value = null;

  // 重置 battleStats
  Object.assign(battleStats, {
    playerScore: 0,
    aiScore: 0,
    round: 1,
    totalRounds: 5,
    timeRemaining: 15,
    playerCorrect: 0,
    aiCorrect: 0,
  });

  // 重置 teamBattleStats
  Object.assign(teamBattleStats, {
    playerTeamScore: 0,
    aiTeamScore: 0,
    round: 1,
    totalRounds: 6,
    timeRemaining: 20,
    playerTeamCorrect: 0,
    aiTeamCorrect: 0,
    currentPlayerIndex: 0,
    completedChallenges: [],
  });

  // 重置 pvpBattleStats
  Object.assign(pvpBattleStats, {
    player1Score: 0,
    player2Score: 0,
    player1Correct: 0,
    player2Correct: 0,
    round: 1,
    totalRounds: 5,
    timeRemaining: 15,
    currentQuestion: 1,
  });
  Object.assign(currentStats, {
    round: 1,
    player1Score: 0,
    player2Score: 0,
    playerTeamScore: 0,
    aiTeamScore: 0,
    playerScore: 0,
    aiScore: 0,
    player1Correct: 0,
    player2Correct: 0,
    playerTeamCorrect: 0,
    aiTeamCorrect: 0,
    playerCorrect: 0,
    aiCorrect: 0,
    timeRemaining: 15,
  });
};
const handleTabChange = (tab) => {
  activeTab.value = tab;
};
const formatDate = (date) => {
  return date.toLocaleDateString();
};
const getDifficultyText = (difficulty) => {
  switch (difficulty) {
    case "easy":
      return "简单";
    case "medium":
      return "中等";
    case "hard":
      return "困难";
    default:
      return "混合";
  }
};
const difficultyOptions = ref([
  {
    id: "easy",
    icon: "mdi:shield",
    name: "简单",
    desc: "适合新手，题目相对容易",
    color: "from-gray-200 to-gray-300",
    iconColor: "text-gray-600",
    tag: "新手推荐",
  },
  {
    id: "medium",
    icon: "mdi:target",
    name: "中等",
    desc: "平衡挑战，适合大多数玩家",
    color: "from-gray-200 to-gray-300",
    iconColor: "text-gray-600",
    tag: "热门选择",
  },
  {
    id: "hard",
    icon: "mdi:fire",
    name: "困难",
    desc: "高难度挑战，考验真实水平",
    color: "from-gray-200 to-gray-300",
    iconColor: "text-gray-600",
    tag: "高手对决",
  },
  {
    id: "mixed",
    icon: "mdi:star",
    name: "混合",
    desc: "随机难度，保持新鲜感",
    color: "from-gray-200 to-gray-300",
    iconColor: "text-gray-600",
    tag: "趣味无穷",
  },
]);
// 方法
const cancelSearch = () => {
  isSearching.value = false;
  searchTime.value = 0;
};

const startBattle = () => {
  // 开始对战逻辑
  pvpMode.value = "battle";
  opponent.value = mockOnlinePlayers[1];
  phase.value = "battle";
  battleMode.value = "solo";
  console.log("开始对战");
};

// 响应式数据
const recentMatches = ref([
  {result: "W", opponent: "策略大师", score: "85-72"},
  {result: "W", opponent: "R.O.O.K.I.E", score: "92-68"},
  {result: "L", opponent: "终极智脑", score: "76-89"},
  {result: "W", opponent: "闪电侠", score: "81-79"},
  {result: "W", opponent: "策略大师", score: "88-74"},
]);

const getAIStatusText = (type) => {
  switch (type) {
    case "thinking":
      return t('script.aiStatusThinking');
    case "answering":
      return t('script.aiStatusAnswering');
    case "completed":
      return t('script.aiStatusCompleted');
    case "waiting":
      return t('script.aiStatusWaiting');
  }
};

const finishBattle = () => {
  battleStarted.value = false;

  let currentStats,
    playerScore,
    opponentScore,
    correctAnswers,
    totalRounds,
    testTypeName;

  if (pvpMode.value === "battle") {
    // PvP对战
    currentStats = pvpBattleStats;
    playerScore = currentStats.player1Score;
    opponentScore = currentStats.player2Score;
    correctAnswers = currentStats.player1Correct;
    totalRounds = currentStats.totalRounds;
    testTypeName = "真人对战";
  } else if (battleMode.value === "team") {
    // 团队对战
    currentStats = teamBattleStats;
    playerScore = currentStats.playerTeamScore;
    opponentScore = currentStats.aiTeamScore;
    correctAnswers = currentStats.playerTeamCorrect;
    totalRounds = currentStats.totalRounds;
    testTypeName = "AI团队对战";
  } else {
    // 单人AI对战
    currentStats = battleStats;
    playerScore = currentStats.playerScore;
    opponentScore = currentStats.aiScore;
    correctAnswers = currentStats.playerCorrect;
    totalRounds = currentStats.totalRounds;
    testTypeName = "AI对战综合测试";
  }

  const playerWins = playerScore > opponentScore;
  const isDraw = playerScore === opponentScore;

  const result = playerWins ? "victory" : isDraw ? "draw" : "defeat";
  battleResult.value = result;
  phase.value = "result";

  const finalScore = Math.min(
    100,
    Math.round((correctAnswers / totalRounds) * 100)
  );

  const testResult = {
    id: Date.now().toString(),
    testType: testTypeName,
    score: finalScore,
    maxScore: 100,
    date: new Date(),
    duration:
      totalRounds *
      (pvpMode.value === "battle" ? 15 : battleMode.value === "team" ? 20 : 15),
    percentile: Math.max(1, Math.min(99, finalScore + Math.random() * 20 - 10)),
    details: {
      battleMode: true,
      pvpMode: pvpMode.value === "battle",
      teamMode: battleMode.value === "team",
      opponent:
        pvpMode.value === "battle" ? opponent.value?.id : selectedAI.value.id,
      winner: playerWins ? "player" : "opponent",
      rounds: totalRounds,
      playerScore: playerScore,
      opponentScore: opponentScore,
      playerCorrect: correctAnswers,
      opponentCorrect:
        pvpMode.value === "battle"
          ? currentStats.player2Correct
          : battleMode.value === "team"
            ? currentStats.aiTeamCorrect
            : currentStats.aiCorrect,
    },
  };

  // 保存测试结果，让用户手动选择
  finalTestResult.value = testResult;
};

const battleData = computed(() => {
  if (pvpMode.value === "battle") {
    return {
      playerScore: pvpBattleStats?.player1Score || 0,
      opponentScore: pvpBattleStats?.player2Score || 0,
      opponentName: opponent?.name || "对手",
      opponentAvatar: opponent?.avatar || "🤖",
    };
  } else if (battleMode.value === "team") {
    return {
      playerScore: teamBattleStats?.playerTeamScore || 0,
      opponentScore: teamBattleStats?.aiTeamScore || 0,
      opponentName: `${selectedAI?.name}团队`,
      opponentAvatar: selectedAI?.emoji || "🤖",
    };
  } else {
    return {
      playerScore: battleStats?.playerScore || 0,
      opponentScore: battleStats?.aiScore || 0,
      opponentName: selectedAI?.name || "AI",
      opponentAvatar: selectedAI?.emoji || "🤖",
    };
  }
});

// 处理方法
const handleComplete = () => {
  if (finalTestResult.value) {
    emit("complete", finalTestResult.value);
  }
};
</script>
